Re: reading numbers of words and lines in text file in C++

From: Rolf Magnus (ramagnus_at_t-online.de)
Date: 12/08/04


Date: Wed, 08 Dec 2004 20:36:37 +0100

sahm wrote:

> #include <iostream>
> #include <fstream>
> #include <string>
> #include <sstream>
>
> using namespace std;
>
> int main()
> {
> string fileName;
> char c;
> cout << endl;
> cout << "Enter the name of the file: ";
> cin >> fileName;
> cout << endl << endl;
>
> //declares filename
> ifstream d_file;
> d_file.open(fileName.c_str()); //attempts to open file
>
> if (!d_file.is_open())
> {
> //if file doesn't exist; don't create a new one
> cout << "File " << fileName << " does not exist in the
> client's current directory" << endl;
> system("pause");
> exit(1);
> }
> else
> {
> d_file.get(c);
> d_file.seekg(0, ios::end);
> int charCount = d_file.tellg();
> d_file.seekg (0, ios::beg);
> //prints the number of characters in a file;
> cout << "the number of characters in the " << fileName;
> cout << " is " << charCount << endl;
>
> //prints the number of lines in a file
> string t;
> int lineCount=0;
>
> while(getline(d_file, t, '\n'))
> ++lineCount;
>
> cout << "The number of lines in the file is " <<
> lineCount << endl;
>
> //reads the number of lines in a file, then print
> int wordCount=0;
> string word;
>
> for (;;)
> {
> d_file >> word;
> if ( d_file.eof() ) { break;}
> wordCount++;
> }
> cout << wordCount << endl;
> }
> d_file.close();
> system("pause"):
> return 0;
> }
>
> ******
> i got the read number of lines and characters in d file worked right
> except for the wordCount, it kept on giving me a 0....

That's logical. You open a file, read it until the end to get the line
count, then you try to read on to get the word count. Since you're already
at the end of file, you break out of the loop immediately and the count
stays at 0. Seek to the beginning and restet the stream's eof flag after
the first loop.



Relevant Pages