我需要获取一个参数并将其转换为一个 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/