这是我正在练习的一些代码编程:使用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;
}
}
它正在按预期工作,但我注意到它没有检测到重复的第一个字 - 例如“run run”将没有返回,“run run run”会告诉我重复单词2但不是单词编号1.出于好奇,我需要在此代码中更改以检测单词1是否重复?
答案 0 :(得分:1)
有了这个,你正在跳过第一个词:
cin >> current;
while (cin >> current) {
编辑:由于第一个单词无法与任何内容进行比较,我们可以将第一个单词的值设置为previous,并从第二个单词开始比较:
cin >> previous;
while (cin >> current) {
答案 1 :(得分:0)
只需准确编码您想要的内容。这是一种方式:
#include <iostream>
using namespace std;
int main()
{
int numberOfWords = 1;
bool previousMatch = false;
string previous; // the operator >> skips white space
string current;
cout << "Type some stuff." << std::endl;
cin >> previous;
while (cin >> current)
{
if (previous == current)
{
if (! previousMatch)
{ // Previous word repeated too
cout << "word number " << numberOfWords
<< " repeated: " << current << '\n';
previousMatch = true;
}
cout << "word number " << numberOfWords + 1
<< " repeated: " << current << '\n';
}
else
previousMatch = false;
++numberOfWords; // increase word count
previous = current;
}
}