如果用户不小心给出了错误的数据类型,cin 是如何工作的?

How cin works if user accidentally gives incorrect datatype?

我是 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 因为 int0.14 将在缓冲区中所以当第二个 >>遇到它会将 0 分配给 v2 并且第 3 个 >>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

你读了一个花车。未读取任何内容,因为已设置故障位。

当std::cin读入无效输入时,std::cin进入"fail state"。无法再读入,有时失败状态会导致错误或向终端发送垃圾邮件。要退出失败状态,您可以使用 std::cin.clear() 函数。此外,当您使用 std::cin.clear() 时,我还建议使用 std::cin.ignore(10000,'\n') 来清除 cin 并防止进一步失败。