简体   繁体   中英

unable to open file in C++

I am trying to open these two files and read their contents into two different arrays, but whenever I try and open them I get the unable to open file dialog? I don't see anything incorrect but I am not a strong c++ user.

std::ifstream inFile;

inFile.open("fives.txt"); 
if (inFile.is_open()) 
{
    while (! inFile.eof() ) 
    {
        getline (inFile,line);
        fives[loop] = line;
        cout << fives[loop] << endl; 
        loop++;
    }
    inFile.close(); 
}
else cout << "Unable to open file";

inFile.open("search.txt");
loop=0;
if (inFile.is_open()) 
{
    while (! inFile.eof() ) 
    {
        getline (inFile,line);
        search[loop] = line;
        cout << search[loop] << endl; 
        loop++;
    }
    inFile.close(); 
}
else cout << "Unable to open file";

The files must exist in the current directory , where the current directory is the directory from which the program was executed (not necessarily the one where the executable is saved at).

In your case, you saved the files with the resources, not with the resulting binary (I'm guessing you're running from within the VC++, by default it sets the current directory to where the binary is stored), so the program cannot find them. Use either relative path to where the resources are, or copy the files you're looking for into the directory you're running from.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM