【问题标题】:Counting same string/word in a text file in C++在 C++ 的文本文件中计算相同的字符串/单词
【发布时间】: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


【解决方案1】:

因为这两个两个在同一行,并且您只在该行中搜索一个子字符串。
您找不到 '\n',因为 getline 函数会读取包含和不包含 '\n' 的行。

【讨论】:

    【解决方案2】:

    为什么不使用std::multisetstore the words?它会为您提供do the counting,并且可以在一行中将文件读入其中:

    #include <iostream>
    #include <fstream>
    #include <string>
    #include <set>
    #include <iterator>
    
    int main(int argc, const char** argv)
    {
        // Open the file
        std::ifstream input(argv[1]);
    
        // Read all the words into a set
        std::multiset<std::string> wordsList = 
            std::multiset<std::string>( std::istream_iterator<std::string>(input),
                                        std::istream_iterator<std::string>());
    
        // Iterate over every word
        for(auto word = wordsList.begin(); word != wordsList.end(); word=wordsList.upper_bound(*word))
            std::cout << *word << ": " << wordsList.count(*word) << std::endl;
    
        // Done
        system("pause");
        return 0;
    }
    

    请注意最后一个 for 部分 - word=wordsList.upper_bound(*word)。从技术上讲,您可以将其切换为简单的word++(实际上最好将其缩短为简单的for(auto word: wordList)。它确保集合中的每个值只会输出一次。

    它还会列出单词本身,而无需像现在在当前的 while 循环中那样做。

    【讨论】:

      【解决方案3】:

      最好的办法是阅读每一行,然后沿着空白进行标记,这样你就可以单独检查每个单词。

      我怀疑我们在这里讨论的是家庭作业,所以我最好的答案是引导你到 std::strtok 的 c++ 参考:http://en.cppreference.com/w/cpp/string/byte/strtok

      【讨论】:

        猜你喜欢
        • 2013-06-25
        • 1970-01-01
        • 2017-10-26
        • 1970-01-01
        • 2020-08-08
        • 1970-01-01
        • 1970-01-01
        • 2015-07-13
        相关资源
        最近更新 更多