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

C++中cin连续输入整数时跳过第二个输入问题求助

解决C++中cin跳过输入的问题

你遇到的问题本质是cin读取整数时会自动忽略空白字符(空格、换行、制表符):当你一次性输入5 10后,第一个cin >> asd1取走了缓冲区里的5,剩下的10和换行符还留在输入缓冲区中。第二个cin >> asd2会直接读取缓冲区里的10,根本不会等待用户输入,导致输出格式混乱。

解决方案1:读取后清空输入缓冲区

每次读取整数后,用cin.ignore()清空缓冲区中剩余的所有字符直到换行符,这样下一次cin就会等待用户输入。需要包含<limits>头文件来使用numeric_limits。

修改后的代码:

#include <iostream>
#include <limits>

using namespace std;

int main() {
    int asd1, asd2;

    cout << "Enter the first one: ";
    cin >> asd1;
    // 清空缓冲区直到换行,避免剩余内容影响下一次输入
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cout << endl;
    if (asd1 == 5) {
        cout << "First one is 5" << endl;
    }

    cout << "Enter the second one: ";
    cin >> asd2;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cout << endl;
    if (asd2 == 10) {
        cout << "Second one is 10" << endl;
    }
}

解决方案2:先读取整行再解析整数

用getline读取整行输入,再通过stringstream从行中提取整数,这样不管用户一行输入多少内容,都不会影响下一次输入。需要包含<string>和<sstream>头文件。

修改后的代码:

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main() {
    int asd1, asd2;
    string inputLine;

    cout << "Enter the first one: ";
    getline(cin, inputLine);
    stringstream ss(inputLine);
    ss >> asd1;
    cout << endl;
    if (asd1 == 5) {
        cout << "First one is 5" << endl;
    }

    cout << "Enter the second one: ";
    getline(cin, inputLine);
    stringstream ss2(inputLine);
    ss2 >> asd2;
    cout << endl;
    if (asd2 == 10) {
        cout << "Second one is 10" << endl;
    }
}

为什么cin.get()没用?

cin.get()默认只读取一个字符,如果缓冲区里剩下的是10\n,它只会取走第一个'1',剩下的'0'和'\n'还在缓冲区里,第二个cin依然会读取'0',所以无法解决问题。只有清空到换行符,才能彻底清除缓冲区的剩余内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 14:13:13