简体   繁体   English

我如何获得一个C ++程序来计算用户输入时的单词数?

[英]How do I get a C++ program to count the number of words as a user enters input?

I'm trying to write a program that keeps taking input from the user until the user enters "quit." 我正在尝试编写一个程序,该程序将不断从用户那里获取输入,直到用户输入“退出”为止。 Each time the user enters input, I want the program to print out the number of words the user has entered. 每次用户输入输入时,我都希望程序打印出用户输入的单词数。 So the following input on the user's part: 因此,用户输入以下内容:

hello how are you

would yield the following output: 将产生以下输出:

You entered 4 words.

However, I am having trouble writing the program so that it counts the number of words on just one line; 但是,我在编写程序时遇到麻烦,因此它只能计算一行上的单词数; it doesn't clear the number before going onto the next line. 在进入下一行之前不会清除数字。 So, if it took input from the user three times, it would add up the total number of words on those three lines. 因此,如果它接受了来自用户的三遍输入,则这三行中的单词总数将相加。 For example, the following input: 例如,以下输入:

how are you
i am good thank you
quit

would yield the following output: 将产生以下输出:

 You entered 9 words.

when I want it to output the number of words following each line the user enters (except quit), ie 当我希望它输出用户输入(退出除外)的每一行之后的单词数时,即

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

Here's the relevant bit of my code: 这是我的代码的相关部分:

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;

I'd rather not use something like a vector; 我宁愿不要使用类似矢量的东西。 whatever I use will need to be converted to a *char eventually because my global variable is a *char. 最终由于我的全局变量是* char,因此我使用的任何内容最终都需要转换为* char。 (And my global variable is a *char because, depending on certain conditions, *input may be set to *argv[] from main.) (我的全局变量是* char,因为根据某些条件,* input可能会从main设置为* argv []。)

I've tried all sorts of things, but I just can't seem to get past the fact that strcmp(input, quit) compares one word of the input at a time to quit rather than comparing the entire input line to quit. 我已经尝试过各种方法,但似乎似乎无法克服以下事实:strcmp(input,quit)一次比较输入的一个单词以退出,而不是比较整个输入行以退出。 HELP. 救命。

None of your requirements precludes the use of std::string and std::vector . 您的要求均不排除使用std::stringstd::vector I recommend you use them. 我建议您使用它们。

#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);
}

You should use getline() to get an entire line of input into some buffer. 您应该使用getline()将整个输入行输入某个缓冲区。 Then, process that buffer of input to count the number of words in it. 然后,处理该输入缓冲区以计算其中的单词数。 Assuming you define each word to be a block of characters separated by a space. 假设您将每个单词定义为一个由空格分隔的字符块。 Myself, I am a fan of strtok() for breaking up a buffer. 我本人是strtok()的爱好者,因为他破坏了缓冲区。

An alternative approach, just for fun: 一种有趣的替代方法:

#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;
            }
        });
}

Doesn't waste resources by tokenizing a line into a vector :) 不会通过将行标记为向量来浪费资源:)

I would call distance 我会打电话给距离

#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";
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C ++循环:如何使程序在用户输入无效输入时多次重复“错误”消息 - C++ loops: how to get program to repeat “error” message more than once anytime user enters invalid input 当我请求号码但用户输入非号码时,如何防止失控的输入循环? - How do I prevent a runaway input loop when I request a number but the user enters a non-number? 如何从 C++ 的输入中获取特定数字? - How do I get a specific number from an input in c++? 我如何让用户在 C++ 中选择一个数字 - How do i get a user to pick a number in c++ 如果用户输入字母而不是数字,如何循环返回 C++ - how to loop back if a user enters a letter instead of a number c++ 如何检查用户是否输入两次相同的号码? C ++帮助? - How can I check whether a user enters the same number twice? C++ Help? 如果用户在C ++中输入字符串,如何检查此目录中是否有该名称的文件,其扩展名是什么? - If a user enters a string into C++ how do I check if there is a file in this directory with that name and what it's extension is? 用户在C ++中输入行和列后如何打印井字游戏板 - How do I print a tic-tac-toe board after the user enters in the rows and columns in c++ 如果用户在结构中输入某个单词,如何从循环中中断? C ++ - How do I break from a loop if a user enters a certain word into a structure? C++ 如果用户从数组中输入数字,如何获取二维数组的索引 - How do i get the index of a 2D array if the user enters a number from the array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM