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;
}
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.