当我输入 2 个带空格的整数输入时,它会跳转到第二个 cin 函数

When I enter 2 integer inputs with a space it jumps to the second cin function

提问人:Talha Eren 提问时间:10/29/2023 最后编辑:ChrisMMTalha Eren 更新时间:10/29/2023 访问量:44

问:

因此,当我尝试输入程序所需的输入时,我希望用户逐个输入它们。当我同时进入它们两个时,它们之间有一个空格,例如:

5 10

它直接进入第二段。cin

#include <iostream>

using namespace std;

int main() {
    int asd1, asd2;

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

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

当我同时输入两个输入时,它会以一种丑陋的方式输出,这就是我问这个问题的原因。

输出:

Enter the first one: 5 10

First one is 5
Enter the second one:         <<<< Here it doesn't cin.
Second one is 10

我尝试使用但没有真正起作用。cin.get()

C++ 用户输入 CIN

评论

2赞 ChrisMM 10/29/2023
两者都在运行,并按预期工作。如果你的意图是强制用户在两行单独的行上输入两个数字,那么你需要忽略输入,直到看到新行。cin
1赞 Andrej Podzimek 10/29/2023
那是因为你想要的是.std::getline()
0赞 Eljay 10/29/2023
auto get_int(istream& in) -> int { string line; getline(in, line); istringstream ss(line); int result; if (ss >> result) return result; throw "nope"; }
0赞 David C. Rankin 10/29/2023
使用 时必须验证每个输入。如果你滑倒并撞到会发生什么?当我输入一个字母时,请参阅 cin 输入(输入是 int),...行生成输入,然后从该行解析您需要的内容(例如 然后或是一种更宽容的方式)std::cin'r''5'getline()std::stringstreamstd::stoi()

答:

0赞 Chris 10/29/2023 #1

第一个读取语句:从缓冲区读取,但保留在该缓冲区中。第二个读取语句:能够立即从缓冲区读取,而无需执行任何进一步的操作。cin >> asd1510cin >> asd210

如果您希望忽略该输入的其余部分,则需要使用 将整行读入字符串,然后解析第一个输出并将其分配给 和。5 10std::get lineintasd1asd2

例如,您可以编写一个函数来执行此操作。请记住,这具有零错误检查。

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

int get_int_line(std::istream &in) {
    std::string line;
    std::getline(in, line);
    std::istringstream sin(line);
    int i;
    sin >> i;
    
    return i;
} 

在这一点上,你可以写:

int asd1 = get_int_line(std::cin);