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

为什么输入stop后我的C++ while循环没有正常停止运行?

C++ 输入stop无法终止while循环问题说明

问题现象

  • 最初编写的循环逻辑如下,预期输入stop后终止循环,但实际输入后仅出现空行,循环未退出
bool stopped = false;
while (!stopped) {
  string input;
  cin >> input;
  if (input == "stop") {
    stopped = true;
  }
}
  • 完整业务代码如下:
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>

using namespace std;

int main() {
  bool stopped = false;
  ofstream script;
  string scriptname;
  getline(cin >> ws, scriptname);
  script.open(scriptname);
  while (!stopped) {
    string input;
    cin >> input;
    if (input == "line") {
      string lineInput;
      getline(cin >> ws, lineInput);
      int i = lineInput.find(',');
      lineInput[i] = ':';
      script << lineInput << endl;
    } else if(input == "wait") {
      string waitInput;
      getline(cin >> ws, waitInput);
      if (!(waitInput.find(',') != string::npos)) {
        script << "***" << endl;
      } else {
        script << "***" << waitInput << endl;
      }
    } else if(input == "action") {
      string actionInput;
      getline(cin >> ws, actionInput);
      int i = actionInput.find(',');
      actionInput += ')';
      actionInput.insert((i + 2), 1, '(');
      script << actionInput << endl;
    } else if(input == "stop") {
      stopped = true;
    }
  }
  script.close();
  return 0;
}

复现步骤

  • 运行程序后输入test按回车,作为输出文件名
  • 继续输入stop按回车,可观察到程序生成了对应的test文件,但界面仅显示空行,循环未退出,程序未终止。

根因与解决方案

代码本身逻辑无问题:cin >> input默认以空白符(空格、换行、制表符等)作为输入分隔,输入stop加回车会被正确读取为字符串stop,触发分支将stopped设为true后循环会正常终止。
实际问题出在运行环境:使用Atom编辑器的集成运行包执行代码时,该插件存在输入流处理异常,未将输入的stop正确传递给程序。改用Konsole终端直接运行编译后的可执行文件,功能完全正常,输入stop可正常终止程序。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 18:15:08