从输入缓冲区读取

Reading from input buffer

本文关键字:读取 缓冲区 输入      更新时间:2023-10-16
void dr1() {
int num1 = 0, num2 = 0;
char str[100];  
while (str[0] != '|') {
cout << "Please enter two numbers (enter "|" to terminate): ";
cin >> num1;
cin >> num2;
cin.getline(str, 100);
cout << num1 << num2 << endl;
}
}

如果用户输入字符串,变量不应该str从输入缓冲区读取它吗?

根据我所学到的知识,您不能将字符串字符输入到int类型中,因此它们会保留在缓冲区中。如果它们留在缓冲区中,getline()不应该读取缓冲区中剩余的任何输入吗?

如果operator>>无法读取格式化的值,则输入确实留在缓冲区中,并且流也进入错误状态,因此后续读取将被忽略并且也失败。这就是为什么getline()没有按预期读取"|"输入的原因。您需要在格式化读取操作失败后clear()流的错误状态。 例如:

void dr1()
{
int num1, num2;
char str[100];
do
{
cout << "Please enter two numbers (enter "|" to terminate): " << flush;
if (cin >> num1)
{
if (cin >> num2)
{
// use numbers as needed...
cout << num1 << num2 << endl;
continue;
}
}
cin.clear();
if (!cin.getline(str, 100)) break;
if (str[0] == '|') break;
}
while (true);
}