通过错误检查将参数转换为整数
Convert argument to integer, with error checking
我想将命令行中的参数用作整数。我还想使用try/catch块检查是否正确:
int i;
try{
i=atoi(argv[1]);
}catch(int e){
printf("error: need integern");
return 0;
}
但是ATOI似乎接受其他输入,例如字符和符号。我该如何克服这个?
谢谢dalvo
使用 stoi
:
try {
i = std::stoi("1234");
}
catch (std::invalid_argument) {
//error
}
使用 std::stringstream
,只有一个可能会有所帮助的片段。
#include<iostream>
#include<sstream>
#include<algorithm>
#include<locale>
int main(int argc, char** argv){
// it should be a double, but makes easier
// to show ideas above
int i;
std::stringstream sstr(argv[1]);
bool is_all_digit = true;
// i tried to use a std::all_of, but get stuck...
// this for do the same job
// keep in mind thar for double, exponencial, etc
// there should be more valid chars
// If you use only sstr >> i, if argv is, for instance
// '12345asdfg' it will consider 12345.
for(char& c: sstr.str()){
is_all_digit &= std::isdigit(c);
}
if( is_all_digit && !(sstr >> i).fail() )
std::cout << "i == " << i << std::endl;
else
std::cerr << "Could not convert " << argv[1] << " to 'int'" << std::endl;
return 0;
}
相关文章:
- 努力将整数转换为链表。不知道我在这里做错了什么
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 如何在C++中将整数转换为其数字数组
- 尝试将字符串/字符转换为整数会产生意外结果
- 如何使用C++将字符串中的字符转换为整数变量
- 如何将整数字符串转换为整数的二维向量?
- 如果整数与指针大小相同,则重新解释将整数转换为指针双射是否具有双射作用?
- 使用 "stringstream " 将字符串转换为整数
- 将字符串转换为浮点数或整数,而无需使用内置函数(如 atoi 或 atof)
- 如何检测 std::vector::emplace_back 上的隐式转换损失整数精度
- 如何防止双精度值到整数的隐式转换
- 为什么此指针值不能转换为整数的规则是什么?
- 如何解决隐式转换丢失整数精度:'size_t'(又名"无符号长")到'int'警告?
- 在 C++ 中将整数数组转换为位集表示形式的最佳方法?
- 为什么在将 void 指针转换为整数指针时出现分段错误
- 将字符串(可以是十进制字符串或十六进制字符串)转换为整数C++
- 整数类型应该显式转换(例如"int"到"无符号")还是只会增加混乱?
- 如何使用 STL 算法将整数向量转换为字符串向量?
- 无法将"整数 (*)[m]"转换为"整数 (*)[100000]
- 静态强制转换允许转换对象指针,但不允许转换整数