0

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?

Eugene Sh.
  • 17,802
  • 8
  • 40
  • 61
soonoo
  • 867
  • 1
  • 10
  • 35

4 Answers4

0

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.

dwcanillas
  • 3,562
  • 2
  • 24
  • 33
0

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.

Sam
  • 101
  • 1
  • 2
0

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;
IndieTech Solutions
  • 2,527
  • 1
  • 21
  • 36
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;
   }
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270