通过错误检查将参数转换为整数

Convert argument to integer, with error checking

本文关键字:转换 整数 参数 过错 错误 检查      更新时间:2023-10-16

我想将命令行中的参数用作整数。我还想使用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;
}