2011-07-23 43 views
0
#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 

回答

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没有作用)

+0

一旦我做到了,现在我的字计数器功能给我0 –

+0

@Vaios:你使用它们之前,您应该初始化所有变量。如果你不知道他们只是得到一个随机值(包含变量的内存块恰巧是) –

+0

@Vaios:已更新。 – Mat

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; 
+0

什么是格式化输入?我确实从char变成了字符串,我仍然得到0 –

+0

格式化输入使用'>>'运算符。等等,你是从'cin'还是从一个文件读取?它应该是'while(a >> dummy)'我想。 –

+0

来自我读取的文件 –