【发布时间】:2014-11-24 10:34:20
【问题描述】:
我正在尝试从 C++ 中的文本文件中计算相同的字符串/单词。
This is my text file
one two three two
test testing 123
1 2 3
这是我的主程序
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, const char** argv)
{
int counter = 0;
int ncounter = 0;
string str;
ifstream input(argv[1]);
while (getline(input, str))
{
if(str.find("two") != string::npos){counter++;}
if(str.find('\n') != string::npos){ncounter++;}
cout << str << endl; //To show the content of the file
}
cout << endl;
cout << "String Counter: " << counter << endl;
cout << "'\\n' Counter: " << ncounter << endl;
return 0;
}
我正在使用 .find() 函数来查找字符串。 当我插入一个不存在的单词时,它不算数。 当我插入“两个”这个词时,它很重要,但只有一次。
怎么没算2次?
而对于回车(或回车;\n),它不能算任何。这是为什么呢?
【问题讨论】:
-
您应该多次调用
.find以查找该单词的多次出现(如果存在),阅读find的重载以找出最适合您的。
标签: c++ string counter iostream ifstream