【问题标题】:Detect Repeated Words检测重复词
【发布时间】:2021-06-30 18:41:12
【问题描述】:

我是 C++ 的初学者,我正在使用 Bjarne Stroustrup 的 Programming: Principles and Practice。我已经到了作业章节并遇到了这个例子

int main()
{
        string previous = " "; // previous word; initialized to “not a word”
        string current; // current word
        while (cin>>current) { // read a stream of words
                 if (previous == current) // check if the word is the same as last
                     cout << "repeated word: " << current << '\n';
                 previous = current;
        }
}

但我不太明白它背后的逻辑,主要是在循环的第一个过程中,其中 previous=" ",鉴于它的值,我不知道从 current 的输入中,previous 是如何完全等于任何东西的“”。如果我编译并输入“猫猫吃”,它会将 cat 识别为重复的单词,但它怎么知道,就像评论说的那样,它初始化为无单词,为什么它会计算出重复的单词:cat 在第一种情况下。

【问题讨论】:

  • 想想previous = current; 行,它的作用是什么?
  • 它分配一个新值,当前,到以前?
  • 您是否正在编译和运行该示例代码?您应该能够添加一个 cout 语句,在循环内显示 previouscurrent 的值。它产生的输出记录可能会帮助您了解它是如何工作的。好老 printf debugging 这么说。

标签: c++ string cin


【解决方案1】:

在循环迭代结束时,您将当前值分配给前一个 (previous = current)。在新迭代开始时,您将用户输入的值分配给当前值并与之前的值进行比较。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-05
    • 2022-01-07
    • 2016-04-08
    • 2020-08-16
    • 2021-08-16
    • 2020-09-15
    相关资源
    最近更新 更多