Vaios Argiropoulos
Vaios Argiropoulos

Reputation: 387

Counting the number of words in a file

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

using namespace std;

int hmlines(ifstream &a){
int i=0;
string line;
while (getline(a,line)){
cout << line << endl;
i++;

}
return i;

}


int hmwords(ifstream &a){

int i=0;
char c;
while ((c=a.get()) && (c!=EOF)){
if(c==' '){
i++;
}

}

return i;


}








int main()
{
int l=0;
int w=0;
string filename;
ifstream matos;
start:
cout << "give me the name of the file i wish to count lines, words and chars: ";
cin >> filename;
matos.open(filename.c_str());
if (matos.fail()){
goto start;
}
l = hmlines(matos);
matos.seekg(0, ios::beg);
w = hmwords(matos);
/*c = hmchars(matos);*/
cout << "The # of lines are :" << l << ". The # of words are : " << w ;

matos.close();



}

The file that i am trying to open has the following contents.

Twinkle, twinkle, little bat!
How I wonder what you're at!
Up above the world you fly,
Like a teatray in the sky.

The output i get is:

give me the name of the file i wish to count lines, words and chars: ert.txt
Twinkle, twinkle, little bat!
How I wonder what you're at!
Up above the world you fly,
Like a teatray in the sky.
The # of lines are :4. The # of words are : 0

Upvotes: 0

Views: 7621

Answers (2)

Mat
Mat

Reputation: 206929

int hmwords(ifstream &a){
  int i;

You've forgotten to initialize i. It can contain absolutely anything at that point.

Also note that operator>> on streams skips whitespace by default. Your word counting loop needs the noskipws modifier.

  a >> noskipws >> c;

Another problem is that after you call hmlines, matos is at end of stream. You need to reset it if you want to read the file again. Try something like:

l = hmlines(matos);
matos.clear();
matos.seekg(0, ios::beg);
w = hmwords(matos);

(The clear() is necessary, otherwise seekg has no effect.)

Upvotes: 4

Kerrek SB
Kerrek SB

Reputation: 477690

Formatted input eats whitespaces. You can just count tokens directly:

int i = 0;
std::string dummy;

// Count words from the standard input, aka "cat myfile | ./myprog"
while (cin >> dummy) ++i;

// Count files from an input stream "a", aka "./myprog myfile"
while (a >> dummy) ++i;

Upvotes: 4

Related Questions