【发布时间】: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 语句,在循环内显示
previous和current的值。它产生的输出记录可能会帮助您了解它是如何工作的。好老 printf debugging 这么说。