C++ - 使用 Atoi 时出错
C++ - error while using atoi
我正在尝试使用atoi
函数来获得从string
到int
的转换。问题是我有一个包含整数和字符串值的字符串数组。
根据我所读到的内容,为了从中获取错误代码,该函数必须返回 0 :
string s = "ssss";
int i = atoi(s.c_str())
if (i == 0)
cout<<"error"<<endl;
end;
如果我的字符串值0
,我应该怎么做?
另一个问题是这个字符串:string s = "001_01_01_041_00.png"
。atoi
函数返回值 1
。它不应该返回0
.为什么它会返回1
?
atoi
使用不安全的原因。它不会检测并通知程序输入是否无效。
C++11 引入了安全的std:stoi
,因为如果输入以某种方式无效,它会引发异常。还有另外两种变体:std::stol
和std:stoll
。有关详细信息,请参阅联机文档:
-
std::stoi
、std::stol
、std::stoll
你的代码将变成这样:
try {
string s = "ssss";
int i = std::stoi(s); //don't call c_str()
//if (i == 0) no need to check!
std::cout << i << endl;
}
catch(std::exception const & e)
{
cout<<"error : " << e.what() <<endl;
}
请注意,e
的运行时类型可以是std::invalid_argument
,也可以是std::out_of_range
,具体取决于引发的原因。如果您希望它们以不同的方式处理,您可以只编写两个catch
块。
已经有很好的答案推荐 std::stoi 和 boost::lexical_cast 的 C++ API。
atoi() 是一个 C API,在 C 中甚至被破坏,因为除了成功解析零之外,您无法区分失败。如果你正在编写 C,如果你关心错误,请使用 strtol() 和 friends,因为它在 ERRNO 中报告它们带外。
因为001_
中的数字是1,为什么它应该返回0?如果只想处理一个字符,只需使用 isdigit(s[0])
和 s[0]-'0'
。如果要更好地进行错误检查以查看字符串中包含多少数字,请使用 strtol
。
atoi 有点老了......在增强库"词汇演员表"中有一个更好的替代品。
char * str = boost::lexical_cast<std::string>(int_value);
或
int int_value = boost::lexical_cast<int>(string_value);
- 访问者访问变体并返回不同类型时出错
- 在Linux for Windows上编译C++代码时出错
- 读取文件的最后一行并输入到链接列表时出错
- 重载操作程序时出错>>用于类中的字符串 memebr
- 调用专用模板时出错"no matching function for call to [...]"
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- LINK 尝试使用 OpenSSL evp aes 256 c++ 时出错
- 在Google Kick start中提交时出错
- 在c++中访问int到类对象的映射时出错
- 分段错误当我试图运行程序时出错
- 使用dynamic_cast和构造函数时出错
- CHECK(调用)函数在Google Colab中出错
- 用pybind11包装C++抽象类时出错
- 为x86而非x64编译时出错
- 从R调用C++函数并对其进行集成时出错
- 这个函数哪里出错了
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 为重写std::exception的库生成swig接口时出错
- C++ - 使用 Atoi 时出错
- 在字符串到 int 转换中使用 atoi 时出错