如何将命令行参数转换为int?

nos*_*e25 54 c++ argument-passing command-line-arguments

我需要得到一个参数并将其转换为int.到目前为止,这是我的代码:

#include <iostream>


using namespace std;
int main(int argc,int argvx[]) {
    int i=1;
    int answer = 23;
    int temp;

    // decode arguments
    if(argc < 2) {
        printf("You must provide at least one argument\n");
        exit(0);
    }

    // Convert it to an int here

}
Run Code Online (Sandbox Code Playgroud)

Tho*_*mas 85

由于这个答案以某种方式被接受,因此会出现在顶部,虽然它不是最好的,但我已根据其他答案和评论对其进行了改进.

C方式; 最简单,但会将任何无效数字视为0:

#include <cstdlib>

int x = atoi(argv[1]);
Run Code Online (Sandbox Code Playgroud)

输入检查的C方式:

#include <cstdlib>

errno = 0;
char *endptr;
long int x = strtol(argv[1], &endptr, 10);
if (endptr == argv[1]) {
  std::cerr << "Invalid number: " << argv[1] << '\n';
} else if (*endptr) {
  std::cerr << "Trailing characters after number: " << argv[1] << '\n';
} else if (errno == ERANGE) {
  std::cerr << "Number out of range: " << argv[1] << '\n';
}
Run Code Online (Sandbox Code Playgroud)

使用输入检查的C++ iostream方式:

#include <sstream>

std::istringstream ss(argv[1]);
int x;
if (!(ss >> x)) {
  std::cerr << "Invalid number: " << argv[1] << '\n';
} else if (!ss.eof()) {
  std::cerr << "Trailing characters after number: " << argv[1] << '\n';
}
Run Code Online (Sandbox Code Playgroud)

自C++ 11以来的替代C++方式:

#include <stdexcept>
#include <string>

std::string arg = argv[1];
try {
  std::size_t pos;
  int x = std::stoi(arg, &pos);
  if (pos < arg.size()) {
    std::cerr << "Trailing characters after number: " << arg << '\n';
  }
} catch (std::invalid_argument const &ex) {
  std::cerr << "Invalid number: " << arg << '\n';
} catch (std::out_of_range const &ex) {
  std::cerr << "Number out of range: " << arg << '\n';
}
Run Code Online (Sandbox Code Playgroud)

所有四种变体都假定为argc >= 2.所有人都接受领先的空白; 检查isspace(argv[1][0])你是否不想这样做.除atoi拒绝尾随空格外的所有内容.

  • 事实上,无法判断转换是否实际发生在`atoi`?这似乎是一个很好的理由避免对我说'atoi`. (9认同)
  • 我建议不要使用atoi:"atoi()函数已被strtol()弃用,不应在新代码中使用." (2认同)
  • @WhirlWind被谁贬低? (2认同)
  • 你介意我们加入一个'stoi`解决方案吗?这会使这个答案更加完整. (2认同)

CB *_*ley 23

请注意,您的main参数不正确.标准表格应为:

int main(int argc, char *argv[])
Run Code Online (Sandbox Code Playgroud)

或等效地:

int main(int argc, char **argv)
Run Code Online (Sandbox Code Playgroud)

有很多方法可以实现转换.这是一种方法:

#include <sstream>

int main(int argc, char *argv[])
{
    if (argc >= 2)
    {
        std::istringstream iss( argv[1] );
        int val;

        if (iss >> val)
        {
            // Conversion successful
        }
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)


Hel*_*rld 10

也可以使用字符串中的std :: stoi.

    #include <string>

    using namespace std;

    int main (int argc, char** argv)
    {
         if (argc >= 2)
         {
             int val = stoi(argv[1]);
             // ...    
         }
         return 0;
    }
Run Code Online (Sandbox Code Playgroud)