C++ - 使用 Atoi 时出错

C++ - error while using atoi

本文关键字:出错 Atoi 使用 C++      更新时间:2023-10-16

我正在尝试使用atoi函数来获得从stringint的转换。问题是我有一个包含整数和字符串值的字符串数组。

根据我所读到的内容,为了从中获取错误代码,该函数必须返回 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::stolstd:stoll。有关详细信息,请参阅联机文档:

  • std::stoistd::stolstd::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);