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

标签 c++

这是我在 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/

相关文章:

没有初始化就使用 C++ 变量?

c++ - 如何强制在派生类中调用基类构造函数?

php - 多个 if() 合而为一

c++ - 如何以简单的方式声明可变参数模板类的类型

c++ - "Proper"错误输入/行为时退出 C/C++ 程序的方法

c++ - 具有成员变量的 Const 对象数组 = 先前索引成员变量的总和

c++ - strace 会阻止程序的正确执行吗?

c++ - "cast to first member of standard layout"类型双关规则是否扩展到数组?

c++ - C++ 中的函数重载和按引用传递

c++ - 如何在 C++ 中将 const ref a 返回给局部变量?