You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++重复单词检测示例代码首次循环运行逻辑疑问

C++示例代码运行逻辑解答

你提到的代码完整可编译版本如下(原示例省略了必要的头文件和命名空间声明):

#include <iostream>
#include <string>
using namespace std;

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;
        }
        return 0;
}

核心运行逻辑解释

你疑惑的点可以通过两个基础规则直接理清:

  • cin >> current读取string类型时,默认会自动跳过所有前置空白字符(空格、换行、制表符等),从第一个非空白字符开始读取,直到遇到下一个空白字符停止,因此读取到的current变量中永远不会包含空格字符。
  • 初始设置previous = " "(值为单个空格的字符串)的作用,就是让它成为一个不可能和任何正常读取到的单词相等的「非单词初始值」,避免第一次循环的比较出现误判。

你输入 the cat cat eats时的完整执行流程

我们按步骤走完全部循环逻辑:

  1. 初始状态:previous值为" ",current为空
  2. 第一次循环:
    • 输入流跳过开头的空格,读取第一个单词the存入current
    • 比较" " == "the",结果为假,不输出重复内容
    • 把previous赋值为"the"
  3. 第二次循环:
    • 读取第二个单词cat存入current
    • 比较"the" == "cat",结果为假,不输出
    • 把previous赋值为"cat"
  4. 第三次循环:
    • 读取第三个单词cat存入current
    • 比较"cat" == "cat",结果为真,输出repeated word: cat
    • 把previous赋值为"cat"
  5. 第四次循环:
    • 读取第四个单词eats存入current
    • 比较"cat" == "eats",结果为假,不输出
    • 把previous赋值为"eats"
  6. 输入流读取完毕,循环结束

整个过程初始的空格值只参与了第一次比较,不会对后续的重复单词判断产生任何干扰,因此可以正常识别出连续重复的cat。

内容的提问来源于stack exchange,提问作者ninoprovezano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 17:42:03