我们是否有以严格的方式将 char* 转换为 int(或 long)的标准方法,即,只有当所有字符都是数字并且可以适合 int(或 long)时,我们才应该得到正确的结果 - 有些通过使用 strtol 等方式..?
因此,使用该函数,“sbc45”、“4590k”、“56”、“56”应该都是无效的。
最佳答案
这是一个与 @GMan 所做的接近的版本,但它不接受前面的空格。例如“101”
:
#include <iostream>
#include <sstream>
#include <iomanip>
#include <string>
#include <exception>
long strict_conversion(const std::string& number_string)
{
long number;
std::stringstream convertor;
convertor << std::noskipws << number_string;
convertor >> number;
if( convertor.fail() || !convertor.eof() )
throw std::runtime_error("The string didn't pass the strict conversion!");
return number;
}
一分钟后,这是通用的:
template <typename NumberType>
NumberType strict_conversion(const std::string& number_string)
{
NumberType number;
std::stringstream convertor;
convertor << std::noskipws << number_string;
convertor >> number;
if( convertor.fail() || !convertor.eof() )
throw std::runtime_error("The string didn't pass the strict conversion!");
return number;
}
关于c++ - 严格字符串转int[long],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3065708/