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

标签 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

}

最佳答案

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

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

#include <cstdlib>

int x = atoi(argv[1]);

带有输入检查的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';
}

带有输入检查的 C++ iostreams 方式:

#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';
}

自 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';
}

所有四个变体都假定 argc >= 2。都接受前导空格;如果您不想这样做,请检查 isspace(argv[1][0])。除了 atoi 之外的所有内容都拒绝尾随空格。

关于c++ - 如何将命令行参数转换为 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2797813/

相关文章:

c++ - 修改一个伪随机数在2个值之间;

callback - 谷歌图表 API : adding arguments to existing callback

c - 如何编写一个 vfprintf 包装器,为格式说明符添加前缀并将新格式说明符传递给 C89 中的 vfprintf?

命令行参数和文件输入

c++ - CLion 2017.1 CMake 在mac OS10.12 上编译报错

C++:Linux平台上的线程同步场景

Python argparse 以不同的方式处理参数

bash - 如何在 linux [bash shell] 中传递 ' [单引号字符] 作为参数?

unix - 记住 *nix 命令行参数

c++ - 如何将Scintilla组件添加到Qt Creator C++项目?