簡體   English   中英

檢測重復的單詞 c++,不檢測第一個單詞

[英]detect repeated word c++, doesn't detect the first word

這是我正在從編程:使用 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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM