c++计算一行中的单词数

c++ counting how many words in line

本文关键字:一行 单词数 计算 c++      更新时间:2023-10-16

我使用这段代码来计算文本的行数,但我还需要计算单词数,并向控制台显示每行中有多少单词。

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;
}

要计算行数和字数,可以尝试将其分解为两个简单的任务:首先使用getline()从文本中读取每一行,其次使用stringstream从一行中提取每一个单词,在每次成功(读取行或提取单词)操作后,可以增加两个表示行数和单词数的变量。

上面可以这样实现:

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;