我想在命令行中使用一个参数作为整数。我还想使用try / catch块来检查它是否是正确的输入:
int i;
try{
i=atoi(argv[1]);
}catch(int e){
printf("error: need integer\n");
return 0;
}
但是atoi似乎接受其他输入,如字符和符号。我怎么能克服这个?
谢谢, dalvo
答案 0 :(得分:3)
使用stoi
:
try {
i = std::stoi("1234");
}
catch (std::invalid_argument) {
//error
}
答案 1 :(得分:0)
使用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;
}