这是我在 Programming: Principles and Practice Using C++ 中练习的一些代码:
#include <iostream>
using namespace std;
int main() {
int numberOfWords = 0;
string previous = " "; // the operator >> skips white space
string current;
cout << "Type some stuff.";
cin >> current;
while (cin >> current) {
++numberOfWords; // increase word count
if (previous == current)
cout << "word number " << numberOfWords
<< " repeated: " << current << '\n';
previous = current;
}
}
它按预期工作,但我注意到它没有检测到重复的 first 词 - 例如“run run”不会返回,“run run run”会告诉我我重复第 2 个单词而不是第 1 个单词。出于好奇,我需要在此代码中更改什么以检测是否重复第 1 个单词?
最佳答案
这样你就跳过了第一个词:
cin >> current;
while (cin >> current) {
编辑:由于第一个词不能与任何东西进行比较,我们可以将第一个词的值设置为前一个并从第二个词开始比较:
cin >> previous;
while (cin >> current) {
关于c++ - 检测重复的单词 c++,不检测第一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33624957/