相关疑难解决方法(0)

如何制作cin >>不将float转换为整数?

我有以下简单的代码:

#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)

c++ integer cin

0
推荐指数
1
解决办法
6241
查看次数

标签 统计

c++ ×1

cin ×1

integer ×1