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

标签 c++ user-input cin

我是 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 和第三个 >> > 将 0.14 分配给 v3,因为 v3float 类型。

请解释一下它是如何工作的。

我在 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/

相关文章:

c++ - cin.getline() 没有将\0 添加到数组 C++ 的末尾

C++ 空格标记 cin 中的输入结束?

c++ - scanf 与 cin : string as integer processing

c++ - 如何获取 `Label::createWithTTF`以支持阿拉伯语等RTL语言

c++ - 如何在模板中返回正确的数据类型?

python - pip install re2 报错

java - 状态管理-【切换状态,重玩游戏】

python - 空用户输入的默认值

c# - .Net OpenCV 包装器值得使用吗?

c - 当我运行代码两次(一段时间/执行一段时间之后)时,scanf 无法按预期工作。 (我使用 Visual C++ Windows 控制台应用程序)