ifstream::good problem in windows and linux !

I have written a program which uses vector::size.

vector<string> myString;

then fill it with some names.

I used myString.size(); to find out the size of vector array.

There is a problem:
In the Vistula stdio and in the eclipse IDe the result is different.

The result of visual stdio is correct but the result of eclipse is 1 number more than real size!


Last edited on
Can you show us the code and output?
I have found the problem in this loop (In the debugging mode):

1
2
3
4
5
6
7
inFile.open("/home/atg/a.txt"):
vector<string> myStr;
while(inFile.good())
{
 inFile >> Line;
 myStr.push_back(Line);
 }


It read one line more than total number of lines in the file (Linux,eclipse)!
The myString.size(); was correct!
Last edited on
Your loop is not correct. If you are actually getting the line, use getline(). Your code should look like one of the following:

1
2
3
4
5
6
inFile.open("/home/atg/a.txt");
vector<string> myStrs;
while (inFile >> Line)  // This only reads one whitespace-delimited string from the file
{
  myStrs.push_back(Line);
}
1
2
3
4
5
6
inFile.open("/home/atg/a.txt");
vector<string> myStrs;
while (getline(inFile,Line))  // This reads an entire line of the file
{
  myStrs.push_back(Line);
}

The first version is good for reading a file like
 
Hello my name is John.
To get a list like:
 
"Hello", "my", "name", "is", "John."

The second is good for reading a file like
1
2
3
Hello.
My name is John.
Nice to meet you.
To get a list like:
 
"Hello.", "My name is John.", "Nice to meet you."

Hope this helps.

[edit] Consider the change. Your loop checks to see whether the file is still good. But inside the loop you attempt to read the file and then use the result without bothering to first check to see if the read succeeded.
Last edited on
Thank you very much.

So this method only useful to get character from a file.
http://www.cplusplus.com/reference/iostream/ifstream/open/
Last edited on
Er, well, that example works, but it is still not a very good example because it copies EOF to cout.

Remember that you must always check for failure immediately after attempting to read anything from a file. Only if the read succeeded can you use the information you got, whether it be a single character or a whole line of them.

Glad to be of help.
Topic archived. No new replies allowed.