命令行参数在不到 3 个 LOC 中 int?

Command line argument to int in less then 3 LOC?

本文关键字:LOC int 参数 命令行      更新时间:2023-10-16

at 如何将命令行参数转换为 int? 它显示了如何将 comand 行参数转换为 int。

我正在寻找捷径。不使用atoi().

int size;
istringstream s(argv[1]);
s >> size;

有了所有很酷的C++11/14/17,我还需要 3 个 LOC?还是周围有int size = magic(argv[1])

您可以使用std::atoi

int size = std::atoi(argv[1]);

请注意,它提供了可怕的错误报告 - 它只是返回0无法执行转换。更好的选择是std::stoi,它接受std::string并在错误时抛出异常:

int size = std::stoi(argv[1]); // note implicit conversion from const char * to std::string