Hello, and thank you for taking time to help me out. For starters, I already know what I was doing wrong and found out how to solve the bug I was experiencing, but I don't know why what I did fixed it.
From the title, you know that I'm working with file handling, so I'll post what's in the file as well as the code. Here is the code in its entirety:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream testfile("test.txt");
if(!testfile.is_open())
{
cout << "Error: file could not be opened.\n";
return 1;
}
int derp;
testfile.seekg(0, ios::beg);
if(testfile >> derp)
{
cout << derp << endl;
}else{
cout << "Shit has hit the fan in point 1.\n";
}
testfile.seekg(0, ios::beg);
if(testfile >> derp)
{
cout << derp << endl;
}else{
cout << "Shit has hit the fan in point 2.\n";
}
testfile.close();
return 0;
}
|
P.S.: Feel free to comment on my code. I'm open for improvements and constructive criticism.
Currently, the text file "test" contains this:
2
As you can see in the code, I'm trying to extract the same data from the file two times. I didn't think this to be a problem, until it didn't work in the real thing I was working with (the above code would output the error message for the second time it attempted to extract the same information).
After about a half an hour of troubleshooting, I found out that, if I put a space after the only character in the file, it works perfectly, and no error messages are displayed.
So, in conclusion, still using the same code as first stated, if the text file
"test" contains this:
the output is this:
2
Shit has hit the fan in point 2.
|
But, if the text file "test" contains this:
the output is would be this:
(runs perfectly like I want it to.)
I am relatively new to C++ and file handling, and by no means any form of an expert. If anyone could explain why this happens and possibly give me / point me in the direction of a good tutorial on this subject, I would be very thankful.
Thank you for taking the time to read this and help me with my question.