c++计算一行中的单词数
c++ counting how many words in line
我使用这段代码来计算文本的行数,但我还需要计算单词数,并向控制台显示每行中有多少单词。
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;
相关文章:
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 从C++dll访问C#中的一行主要参数
- 单步执行代码时重复上一行
- 如何打印以特定字符开头的单词数?
- 将输入作为C 中的单词数组
- 阅读一个大文件来计算重复K次的单词数
- C++ 查找其中字母最少的单词数
- 我的逻辑有什么问题?尝试计算文件中包含特定字符的单词数
- 我需要在接受用户输入后返回 c 刺痛中的单词数
- 计算字符串中的单词数,C++
- 如何输入单词数组c++
- 计算字符数组C++中的单词数
- c++计算一行中的单词数
- 如何通过检查v. dictionary来查找一个短语中删除空格的单词数
- 检测是否在QlistWidget的某一行上单击了某项
- 函数定义计算单词数
- 如何在列表中找到单词数
- 如何获得字符串中的单词数