gpt4 book ai didi

c++ - 在 C++ 中通过错误检查将命令行 char 参数解析为 int

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:29:43 28 4
gpt4 key购买 nike

我正在尝试编写一个接受两个整数作为命令行参数的程序。整数都需要大于 0。我知道我需要从 char 转换,但我只使用 atoi 做过,现在我知道我不应该这样做。我见过人们使用 sstreams 和 strtol 但我不确定在这种情况下它们将如何工作。完成此任务的最佳方法是什么?

#include <iostream>
#include <string>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

using namespace std;

const int N = 7;
const int M = 8;//N is number of lines, M number of values

//--------------
//-----Main-----
//--------------
int main(int argc, char* argv[])
{
if((argc != 0) && (argv[0] != NULL) && (argv[1] != NULL))
{
N = argv[0];
M = argv[1];
}
else
{
cout << "Invalid or no command line arguments found. Defaulting to N=7 M=8.\n\n" << endl;
}


//Blah blah blah code here

return 0;
}

最佳答案

在 C++11 中,有 stoistolstoll 用于此:http://en.cppreference.com/w/cpp/string/basic_string/stol

如果字符串格式不正确,它们会抛出 invalid_argumentout_of_range 异常。

使用 atoi 没有什么特别的错误,除了它没有报告异常的机制,因为它是一个 C 函数。所以你只有返回值 - 问题是 atoi 的所有返回值都是有效值,所以没有办法区分返回值 0 是正确解析“0”还是失败解析。此外,atoi 不检查值是否超出可用值范围。第一个问题很容易通过自己检查来解决,第二个问题更难解决,因为它涉及到实际解析字符串——这首先违背了使用外部函数的意义。

您可以像这样使用 istringstream:

C++11 之前的版本:

int val;
std::istringstream iss(arg[i]);
iss >> val;
if (iss.fail()) {
//something went wrong
} else {
//apparently it worked
}

C++11:

int val;
std::istringstream iss(arg[i]);
iss >> val;
if(iss.fail()) {
if(!value) {
//wrong number format
} else if(value == std::numeric_limits<int>::max() ||
value == std::numeric_limits<int>::min()
{
//number too large or too small
}
} else {
//apparently it worked
}

不同之处在于,在 C++11 之前,仅检测到格式错误(根据标准),而且它不会覆盖错误时的值。在 C++11 中,如果是格式错误,值将被 0 覆盖;如果数字太大或太小而无法适应类型,则值将被 max/min 覆盖。两者都在流上设置失败标志以指示错误。

关于c++ - 在 C++ 中通过错误检查将命令行 char 参数解析为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13846018/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com