Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/144.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ Cin读取数字并检查整数_C++_Numbers_Integer - Fatal编程技术网

C++ Cin读取数字并检查整数

C++ Cin读取数字并检查整数,c++,numbers,integer,C++,Numbers,Integer,Hy 我想用C++函数读取C++中的一个数字。我知道有很多线程,但我没有找到一个perfekt解决方案 首先,我用cin.fail()函数尝试了它。但是如果我输入一个像这样的数字12asdf,它会读取12的正确值,并且不会抛出错误 然后我尝试读取一个字符串并使用atoi()函数对其进行转换,但是如果我读取这样的12asdf字符串,我也会遇到同样的问题。它读取正确的12个字符,并且不会抛出错误 我尝试了该功能,但在visual 2013中无法提供所有功能 if ( std::all_of(inpu

Hy

我想用C++函数读取C++中的一个数字。我知道有很多线程,但我没有找到一个perfekt解决方案

首先,我用cin.fail()函数尝试了它。但是如果我输入一个像这样的数字12asdf,它会读取12的正确值,并且不会抛出错误

然后我尝试读取一个字符串并使用atoi()函数对其进行转换,但是如果我读取这样的12asdf字符串,我也会遇到同样的问题。它读取正确的12个字符,并且不会抛出错误

我尝试了该功能,但在visual 2013中无法提供所有功能

if ( std::all_of(input.begin(), input.end(), std::isdigit) )
{
     //input is integer
}
如何检查像这样的输入12asdf并抛出错误


致意

您可以使用以下功能:

bool is_number(const std::string& s) {
  return !s.empty() && std::find_if(s.begin(),
    s.end(), [](char c) { return !std::isdigit(c); }) == s.end();
}
然后按如下方式使用:

  std::string num;
  std::cout << "Enter number: ";
  std::getline(std::cin, num);
  while (!is_number(num)) {
    std::cout << "Input is not a number , enter again: ";
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    num.clear();
    std::getline(std::cin, num);
  }
std::string num;

std::cout IIRC,
boost::lexical_cast
检查整个字符串。