当前位置:C++技术网 > 精选软件 > C++ Primer Plus 6th 5.9 编程练习题 第8题 统计单词数,用done做结束识别

C++ Primer Plus 6th 5.9 编程练习题 第8题 统计单词数,用done做结束识别

更新时间:2019-05-02 13:13:17浏览次数:1+次

题目:
8.编写一个程序,它使用一个char数组和循环来每次读取一个单词,直到用户输入done为止。随后,该程序指出用户输入了多少个单词(不包括done在内)。下面是该程序的运行情况:

Enter words (to stop, type the word done):
anteater birthday category dumpster
envy finagle geometry done for sure
You entered a total of 7 words.
您应在程序中包含头文件cstring,并使用函数strcmp()来进行比较测试。

答案:  书上无答案。

C++技术网辅导详解解答:
    参考代码:

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
    char words[200] = { 0 };
    int num_word = 0;
    cout << "Enter words(to stop, type the word done) :\n";
    while(true)
    {
        cin >> words;
        if (!strcmp(words, "done"))
            break;
        num_word++;
    }
    cout << "You entered a total of " << num_word << " words.";
    return 0;
}