我使用此代码计算文本行数,但我还需要计算单词并显示以控制每行中有多少单词。
int main(int argc, char *argv[]){
ifstream f1("text.txt"); ;
char c;
string b;
int numchars[10] = {}, numlines = 0;
f1.get(c);
while (f1) {
while (f1 && c != '\n') {
// here I want to count how many words is in row
}
cout<<"in row: "<< numlines + 1 <<"words: "<< numchars[numlines] << endl;
numlines = numlines + 1;
f1.get(c);
}
f1.close();
system("PAUSE");
return EXIT_SUCCESS;
}
答案 0 :(得分:3)
要计算您可以尝试的行数和单词数,并将其制成两个简单的任务:首先使用getline()
从文本中读取每一行,然后使用{从行中提取每个单词{3}},在每次成功(读取行或提取词)操作后,您可以增加两个表示行数和单词数的变量。
以上可以这样实现:
ifstream f1("text.txt");
// check if file is successfully opened
if (!f1) cerr << "Can't open input file.";
string line;
int line_count = 0
string word;
int word_count = 0;
// read file line by line
while (getline(f1, line)) {
// count line
++line_count;
stringstream ss(line);
// extract all words from line
while (ss >> word) {
// count word
++word_count;
}
}
// print result
cout << "Total Lines: " << line_count <<" Total Words: "<< word_count << endl;