【发布时间】:2020-07-27 22:19:27
【问题描述】:
我正在学习 c++ 入门书并做练习 5.14。练习是:
编写一个程序从标准输入中读取字符串 寻找重复的单词。程序应该在输入中找到位置 其中一个词紧跟其后。跟踪最大的 单次重复出现的次数以及重复的单词。打印 重复的最大数量,或者打印一条消息说没有 这个词被重复了。例如,如果输入是 how now now now brown cow cow 输出应该表明单词 now 出现了 3 次。
我的代码如下:
#include <iostream>
#include <string>
using std::string;
using std::cin;
using std::cout;
using std::endl;
int main()
{
string pre_word, word, max_repeate_word;
int repeate_times = 0; max_repeate_times = 0;
while (cin >> word) {
if (word == pre_word) {
++repeat_times;
}
else {
repeat_times = 1;
pre_word = word;
}
if (max_repeat_times < repeat_times) {
max_repeat_times = repeat_times;
max_repeat_word = pre_word;
}
}
if (max_repeat_times <= 1) {
cout << "no word was repeated" << endl;
}
else {
cout << "the word '" << max_repeat_word << "' occurred " << max_repeat_times << " times" << endl;
}
}
我的代码有什么问题吗?当我输入任何字符串时,程序不显示任何输出。
【问题讨论】:
-
建议:将代码剪切并粘贴到 Stack Overflow。当您输入时,插入新错误的几率非常高。
-
在三个错误中我放弃了。
max_repeate_word和max_repeat_times都被多次使用,我不确定它们应该是相同的东西还是不同的变量或完全不同的东西。 -
最后一个想法:你是如何向程序发出你已经停止输入的信号的?
cin是一个流,所以while (cin >> word)会在你停止输入后继续返回更多单词。这可能是你的问题。 -
“我的代码有什么问题,我输入任何字符串时程序没有显示任何输出。” 是的,因为语法错误无法编译.修复错误后,它按预期工作:wandbox.org/permlink/hg2vOnKHyu67H9bJ 你知道如何将 EOF 发送到你的程序吗?如果您的 IDE/终端支持,您可以将输入通过管道传输到您的程序中,或者使用 CTRL+D(对于 *nix)或 CTRL+Z(对于 Windows)发送 EOF。
标签: c++ string if-statement