简体   繁体   中英

How to check EOF when reading txt file using ifstream

I want to read a text file in c++ using ifstream to know the number of words, characters, lines.

unsigned int wordNum = 0;
unsigned int lineNum = 0;
unsigned int charNum = 0;
char check;

ifstream in("example_2_4.txt");
char temp[30];

if (!in.is_open()) {
    cout << "File opening error!" << endl;
}

while (!in.eof()){
    in.getline(temp, 30);

    wordNum += countWord(temp);
    charNum += countChar(temp);
    lineNum++;

    in.clear();
}

The problem is that eof() does not work since there exists a line that exceeds 30 characters.

I've changed !in.eof() to in>>check and it works well but it reads a character so I can't count all characters in line.

I shouldn't use string class and can't change buffer size.

Is there any proper way to check eof ?

I'm not entirely sure what you are asking, but ifstream::getline() sets the failbit when it tries to read a string that's too long. In your case, the eof bit will never be set (even though you are clearing all the bits anyway).

You can simply do:

while (in)

and in addition to not clearing any of the flags.

If you want to be able to read a line that is longer than the buffer you can store it in, you need to read the file some other way, perhaps using ifstream::get() instead.

in.getline(temp, 30); returns istream& so moving it in the while loop to here while(in.getline(temp, 30)) will return false when it reaches the end of file or a read error.

Try this:

  string line;
  ifstream myfile ("example_2_4.txt");
  if (myfile.is_open())
  {
    while ( getline (myfile,line) )
    {
      cout << line << '\n';


    wordNum += countWord(line);
    charNum += countChar(line);
    lineNum++;
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;

Given your constraints, I would suggest:

  1. Read the file character by character.
  2. End the loop when the EOF is reached.
  3. Increment the number of characters.
  4. Check whether the character marks the end of a word. If so, increment the word cound.
  5. Check whether the character is a newline. If so, increment the number of lines.


int c;
while ( (c = in.get()) != EOF )
{
   ++charNum;
   if (isspace(c) )
   {
      ++wordNum;
   }

   if ( c == '\n' )
   {
      ++lineNum;
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM