counter gives output wrong

so i am reading from a file. i am trying to get the number of strings in the file. everytime the counter gives a wrong value
if the file has three strings, it gives four. it is always the real value +1
what is the issue?
1
2
3
4
5
6
7
ifstream infile;
    string q;int counter=0;
    while(!infile.eof())
    {
        infile>>q;
        counter++;
    }cout<<counter;
eof() will return true only after you've tried (and failed) to read string number 4.

Since you increment your counter every time you try to read, whether or not that read is successful, you're not counting the strings; you're counting how many times you tried to read a string.
Last edited on
ah i got it.
thank you so much
Topic archived. No new replies allowed.