#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main () {
string line;
ifstream myfile ("data.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
Hello,
I've been facing a weird problem. When I run my code it just goes to the else statement that says "Unable to open file" but when I start debugging I realized that it actually reads just fine! Does anyone know how to fix this problem?
In VC2010 for me, the debugging directory is not the same as my build directory. So when I hit CTRL+F5 it would run from a different spot. My guess is that the data.txt is in the wrong folder.
OK so now I created a new code which actually opens the file successfully. When I run the code w/o debugging it doesn't go the "while"loop. But when I debug it, it just works fine!!!!!!! OHHHH that's weird!!!!!!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
int main () {
int i;
char *inname = "data.txt";
ifstream infile(inname);
if (!infile) {
cout << "There was a problem opening file "
<< inname
<< " for reading."
<< endl;
return 0;
}
cout << "Opened " << inname << " for reading." << endl;
while (infile >> i) {
cout << "Value from file is " << i << endl;
}
return 0;
}
1 2 3
3
4
5
CAN ANYONE TRY TO RUN THE SAME CODE IN THEIR COMPUTER and SEE IF IT WORKS OR NOT? PLEASE!!!
If you're using visual studio, the debugging will run from the same directory as the source (.cpp) files by default. If you actually run the excecutable, the file needs to be in the same directory as your .exe.