【问题标题】:How do I get a C++ program to count the number of words as a user enters input?如何让 C++ 程序在用户输入输入时计算字数?
【发布时间】:2012-08-01 17:21:29
【问题描述】:

我正在尝试编写一个程序,该程序一直接收用户的输入,直到用户输入“退出”。每次用户输入时,我希望程序打印出用户输入的字数。所以用户的以下输入:

hello how are you

将产生以下输出:

You entered 4 words.

但是,我在编写程序时遇到了麻烦,它只计算一行的单词数;在进入下一行之前,它不会清除数字。因此,如果它从用户那里输入了三次,它将把这三行上的单词总数相加。例如,以下输入:

how are you
i am good thank you
quit

将产生以下输出:

 You entered 9 words.

当我希望它输出用户输入的每一行之后的单词数时(退出除外),即

>>how are you
<<You entered 3 words.
>>i am good thank you
<<You entered 5 words.
>>quit

这是我的代码的相关部分:

char *input;
int inum;

int inputLoop()
{
    char quit[] = "quit";
    inum = 0; //counts number of words

    while (strcmp(input, quit) != 0)
    {
         cin >> input;
         inum++;
    }
    cout <<"You entered " <<inum <<" words." <<endl;

我宁愿不使用向量之类的东西;我使用的任何东西最终都需要转换为 *char,因为我的全局变量是 *char。 (而且我的全局变量是 *char,因为根据某些条件,*input 可能会从 main 设置为 *argv[]。)

我尝试了各种各样的方法,但我似乎无法理解 strcmp(input, quit) 一次比较输入的一个单词以退出而不是比较整个输入行的事实辞职。帮助。

【问题讨论】:

    标签: c++


    【解决方案1】:

    您的任何要求均不排除使用std::stringstd::vector。我建议你使用它们。

    #include <string>
    #include <sstream>
    #include <iostream>
    #include <vector>
    
    std::vector<std::string> words;
    
    int inputLoop()
    {
        char quit[] = "quit";
        total_words = 0;
    
        std::string line;
        // grab a line at a time
        while(std::getline(std::cin, line) && line != quit) {
            // clear the vector of words
            words.clear();
            // make a string stream to read words from that line
            std::stringstream ss(line);
            // grab all the words into a vector
            std::string word;
            while(ss >> word) {
                 words.push_back(word);
            }
            std::cout <<"You entered " <<words.size() <<" words." <<endl;
        }
    }
    
    int main(int argc, char** argv) {
        // get the data from argv
        words = std::vector<std::string>(argv, argv + argc);
    }
    

    【讨论】:

    • 美丽;这看起来正是我想要的。唯一的问题是现在我收到以下错误消息:error: no match for operator&gt;&gt; in ss &gt;&gt; words
    • 我在这个答案中没有看到任何ss &gt;&gt; words。你确定你复制的正确吗?
    • (我假设你的意思是 ss &gt;&gt; wordss &gt;&gt; words
    • 你为什么要这样做?他根本不是那个意思……虽然应该在外部 while 循环中声明了一个额外的 std::string word; 似乎丢失了。
    • 哦,好吧,我假设是因为我没有看到额外的 std::string word 声明。谢谢!
    【解决方案2】:

    您应该使用getline() 将整行输入获取到某个缓冲区。然后,处理该输入缓冲区以计算其中的单词数。假设您将每个单词定义为由空格分隔的字符块。我自己,我是 strtok() 的粉丝,因为我打破了缓冲区。

    【讨论】:

    • @DeadMG:他顺便推荐了getlinestrtok 在 C 语言中完全没问题,只要你知道它不是线程安全的。
    • @netcoder:除了strtok 需要一个可变的C 风格字符串,并且没有明智的方法可以从C++ std::string 获得一个。它也不是线程安全的 - 对于 OP 的特定情况,这可能是也可能不是问题,但通常无法使用。
    • 我投了反对票是有充分理由的,并清楚地说明了这个理由是什么。这完全是建设性的。
    • @MikeSeymour 我假设他没有使用std::string。为什么我会做这么傻的事,因为我喜欢char *
    • @CatShoes:您链接到对std::getline() 的引用,该引用读入std::string。如果您的意思是std::istream::getline(),那么您无法读取整行 - 您必须选择任意缓冲区大小并处理截断的情况。 std::stringstd::stringstream 对于那些不希望他们的 C++ 看起来像一种完全不同的语言的人来说会更直接。
    【解决方案3】:

    另一种方法,只是为了好玩:

    #include <iostream>
    #include <algorithm>
    #include <iterator>
    
    int main()
    {
        unsigned num = 0;
        std::for_each(
            std::istream_iterator<std::string>(std::cin),
            std::istream_iterator<std::string>(),
    
            [&num](const std::string& s)
            {
                if (s == "quit")
                    std::cin.setstate(std::ios::eofbit);
                ++num;
                if (std::cin.peek() == '\n') {
                    std::cout << "You entered "
                              << num
                              << " word"
                              << ((num == 1) ? "." : "s.")
                              << '\n';
                    num = 0;
                }
            });
    }
    

    不会通过将线标记为向量来浪费资源:)

    【讨论】:

      【解决方案4】:

      我会打电话给距离

      #include <string>
      #include <algorithm>
      #include <iterator>
      #include <iostream>
      #include <sstream>
      
      int main()
      {
          std::string line;
          while(std::getline(std::cin, line) && line != "quit")
          {
              std::stringstream  linestream(line);
              std::cout << "You entered "
                        << std::distance(std::istream_iterator<std::string>(linestream), 
                                         std::istream_iterator<std::string>())
                        << " words\n";
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-12
        • 2022-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-17
        • 1970-01-01
        相关资源
        最近更新 更多