2011-07-23 42 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

來自我讀取的文件 –