提问人:Talha Eren 提问时间:10/29/2023 最后编辑:ChrisMMTalha Eren 更新时间:10/29/2023 访问量:44
当我输入 2 个带空格的整数输入时,它会跳转到第二个 cin 函数
When I enter 2 integer inputs with a space it jumps to the second cin function
问:
因此,当我尝试输入程序所需的输入时,我希望用户逐个输入它们。当我同时进入它们两个时,它们之间有一个空格,例如:
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()
答:
0赞
Chris
10/29/2023
#1
第一个读取语句:从缓冲区读取,但保留在该缓冲区中。第二个读取语句:能够立即从缓冲区读取,而无需执行任何进一步的操作。cin >> asd1
5
10
cin >> asd2
10
如果您希望忽略该输入的其余部分,则需要使用 将整行读入字符串,然后解析第一个输出并将其分配给 和。5 10
std::get line
int
asd1
asd2
例如,您可以编写一个函数来执行此操作。请记住,这具有零错误检查。
#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);
评论
cin
std::getline()
auto get_int(istream& in) -> int { string line; getline(in, line); istringstream ss(line); int result; if (ss >> result) return result; throw "nope"; }
std::cin
'r'
'5'
getline()
std::stringstream
std::stoi()