c++ - 在 C++ 中计算文本文件中的相同字符串/单词

标签 c++ string counter iostream ifstream

我正在尝试从 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/

相关文章:

c++ - CDialogEx构造函数和继承的Create()方法

c++ - 处理重新定义 int 类型(uint16_t、int16_t 等)的代码并且 Boost 不喜欢它

c++ - 如何将库路径添加到编译器

java - 求解表达式的输出未按预期输出

java - Android - 如何在ImageView的右上角添加通知计数器

C++ 将程序分解为函数

java - 如何使用正则表达式从字符串中获取数字?

java - 字符串操作模式

特定数字的 CSS 计数器

javascript - jCarousel、计数器,怎么样?