Vermz
Vermz

Reputation: 33

Two dots in the end of text file in C++

Here's the deal, i have a text file that contain some sentence from a book and i want to read and count the number of sentence in it. One way i found was to count the number of dots in the file. It works fine until the last char. When the reading arrives at the last char (which is a dot) it adds another dots and i double-checked the text file and there is only one dot at the end. When i print each char during the reading process i see the second dot at the end. Here is my code:

#include <string>
#include <iostream>
#include <fstream>

using namespace std;

int main(void)
{
    ifstream files("assommoir.txt");
    char caractere;
    int n = 0;

    if (files.fail() == 0)
    {

        while (files.eof() == 0)
        {
            files >> caractere;
            cout << caractere;
            if (int(caractere) == 46)
                n++;
        }
        cout << n << "\n";
    }
    else
        cout << "reading problem detected" << endl;
}    

Upvotes: 0

Views: 1046

Answers (2)

zneak
zneak

Reputation: 138171

files.eof() is true once you've tried to read a character past the last one, not once you've read the last one. Because of this, files.eof() succeeds after the last character, but the flag is raised after you do files >> caractere. Since you don't check at this point, caractere is unmodified (it remains a point) and your program goes on until it loops again.

You should use while (files >> caractere), since input streams are convertible to a boolean value that indicates if it's in a valid state or not.

Upvotes: 4

Tony Delroy
Tony Delroy

Reputation: 106196

Just use while (files >> caractere).

while (files.eof() == 0) is broken - eof is only false after you've tried to read something that's not there (consider that when eof() is called it doesn't know what you'll try to read next - could be the next non-whitespace character or any single character or a number - for some types of data and whitespace-skipping behaviours eof() will be hit and for others not).

Upvotes: 1

Related Questions