我是 C++ 新手。我正在试验 cin
的功能和限制。
我想知道如果用户提供不正确的数据类型,cin
将如何接受输入。所以我检查了 Stack Overflow 并得到了 this answer :
When you read an integer and you give it an input of 1.5, what it sees is the integer 1, and it stops at the period since that isn't part of the integer. The ".5" is still in the input. This is the reason that you only get the integer part and it is also the reason why it doesn't seem to wait for input the second time.
To get around this, you could read a float instead of an integer so it reads the whole value, or you could check to see if there is anything else remaining on the line after reading the integer.
所以我尝试了一下。
#include <iostream>
int main()
{
std::cout << "Enter 4 numbers: " <<
std::endl;
int v1 = 0, v3 = 0;
float v2 = 0, v4 = 0;
std::cin >> v1 >> v2 >> v3 >> v4;
std::cout << "-> " << v1 << " " << v2 << " "
<< v3 << " " << v4 << std::endl;
return 0;
}
Enter 4 numbers:
3.14 2.718
-> 3 0.14 2 0.718
它按预期工作。 但当我尝试时
#include <iostream>
int main()
{
std::cout << "Enter 3 numbers: " <<
std::endl;
int v1 = 0, v2 = 0;
float v3 = 0;
std::cin >> v1 >> v2 >> v3;
std::cout << "-> " << v1 << " " << v2 << " "
<< v3 << std::endl;
return 0;
}
Enter 3 numbers:
3.14
-> 3 0 0
我期待3 0 0.14
,因为3
将是v1
作为int
,0.14
将位于缓冲区中,因此当遇到第二个 >>
时,它将把 0
分配给 v2
和第三个 >>
> 将 0.14
分配给 v3
,因为 v3
是 float
类型。
请解释一下它是如何工作的。
我在 Lenovo Ideapad S340 上使用了 G++ mingw 8.2.0 编译器
最佳答案
If extraction fails, zero is written to value and failbit is set.
输入:3.14
您读取了一个整数。 3
被读取,.14
保留在缓冲区中。
您读取了另一个整数。 .
不是整数的一部分,因此不会读取任何内容,并且 failbit已设置。
你读了一个 float 。没有读取任何内容,因为故障位已经设置。
关于c++ - 如果用户不小心给出了错误的数据类型,cin 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59835693/