我有以下简单的代码:
#include <iostream>
int main()
{
int a;
std::cout << "enter integer a" << std::endl;
std::cin >> a ;
if (std::cin.fail())
{
std::cin.clear();
std::cout << "input is not integer, re-enter please" <<std::endl;
std::cin >>a;
std::cout << "a inside if is: " << a <<std::endl;
}
std::cout << "a is " << a <<std::endl;
std::cin.get();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我运行上面的代码并输入:时1.5,它输出:a is 1.仅供参考:我使用gcc 4.5.3编译并运行代码.
这意味着如果cin期望一个整数但看到一个浮点数,它将隐式地进行转换.那么这是否意味着当cin看到一个浮点数时,它不处于fail()状态?为什么会这样?是因为C++对>>运算符进行隐式转换吗?
我还尝试了以下代码来判断给定的输入数是否是整数,从这篇文章的想法:测试给定的数字是否为整数:
#include <iostream>
bool …Run Code Online (Sandbox Code Playgroud)