计算文件中的单词数

时间:2011-07-23 13:55:32

标签: c++

#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();



}

我尝试打开的文件包含以下内容。

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

我得到的输出是:

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

2 个答案:

答案 0 :(得分:4)

int hmwords(ifstream &a){
  int i;

您忘记初始化i。它可以包含任何东西。

另请注意,默认情况下,流上的operator>>会跳过空白。您的单词计数循环需要noskipws修饰符。

  a >> noskipws >> c;

另一个问题是,在您致电hmlines后,matos即将结束。如果要再次读取文件,则需要重置它。尝试类似:

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

clear()是必要的,否则seekg无效。)

答案 1 :(得分:4)

格式化输入吃空格。你可以直接计算代币:

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;