检测重复的单词 C++,不检测第一个单词

detect repeated word c++, doesn't detect the first word

本文关键字:检测 单词 第一个 C++      更新时间:2023-10-16

这是我正在练习的一些代码,来自编程:使用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重复,我需要在这个代码中更改什么来检测?

这样你就跳过了第一个单词:

cin >> current;
while (cin >> current) {

编辑:由于第一个单词不能与任何东西进行比较,我们可以将第一个单词的值设置为前一个单词,并从第二个单词开始比较:

cin >> previous;
while (cin >> current) {

只需编写您想要的代码。有一种方法:

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