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

C++输入字符'|'时cin跳过不阻塞,如何实现程序正常终止?

问题根源

你当前的写法存在两个核心错误:

  • 调用cin >> number1 >> number2时,输入的|不属于合法的浮点数字符,会直接触发cin的输入失败标记failbit,标记置位后所有后续cin操作都会直接跳过,不会等待用户输入,就会出现程序无限循环的问题
  • 你把字符|强转为double和输入值比较的逻辑完全不成立:输入失败时两个double变量根本不会被写入|对应的数值,这条判断语句永远不会触发

修复方案

建议先把输入内容读取为字符串,先判断是否为终止符|,如果不是再转换为double类型使用,逻辑如下:

  • 每次先读取第一个输入单元为字符串,如果等于|直接终止程序
  • 否则把字符串转为double赋值给number1,再读取第二个输入单元为字符串,同样先判断是不是|,是就终止,否则转成double给number2
  • 额外加非法输入的异常处理,避免输入非数字也非|的内容导致程序出错

修改后可运行的代码如下:

#include "std_lib_facilities.h"
#include <string>

int main()
{
    bool start = true;
    while(start)
    {
        double number1, number2 = 0;
        string input;
        cout << "Enter two doubles, or enter | to exit\n";
        
        // 处理第一个输入
        cin >> input;
        if (input == "|") {
            start = false;
            break;
        }
        try {
            number1 = stod(input);
        } catch (...) {
            cout << "Invalid input, please enter numbers or |\n";
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            continue;
        }

        // 处理第二个输入
        cin >> input;
        if (input == "|") {
            start = false;
            break;
        }
        try {
            number2 = stod(input);
        } catch (...) {
            cout << "Invalid input, please enter numbers or |\n";
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            continue;
        }

        cout << "The value of number1 is: " << number1 << '\n';
        cout << "The value of number2 is: " << number2 << '\n';
    }
    return 0;
}

备选方案(直接处理输入失败状态)

如果你不想用字符串中转,也可以在读取double失败后检查输入流中的字符是否为|:

#include "std_lib_facilities.h"

int main()
{
    bool start = true;
    while(start)
    {
        double number1, number2 = 0;
        cout << "Enter two doubles\n";
        cin >> number1 >> number2;

        if (cin.fail()) {
            // 清空失败标记
            cin.clear();
            char c;
            cin >> c;
            if (c == '|') {
                start = false;
                break;
            }
            cout << "Invalid input\n";
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            continue;
        }

        cout << "The value of number1 is: " << number1 << '\n';
        cout << "The value of number2 is: " << number2 << '\n';
    }
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 23:36:04