我正在尝试从 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),它不能计算任何。这是为什么?
最佳答案
因为两个 twos 在同一行上,而您只在该行中搜索一个子字符串。
您找不到“\n”,因为 getline 函数会读取包含“\n”和不包含“\n”的行。
关于c++ - 在 C++ 中计算文本文件中的相同字符串/单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26109971/