If 语句检查 argv 是否为数字
If statement checks if argv is a number
我的程序中有这个 if
语句,它应该检查启动程序时输入的参数。例如./a.out 2 2 + 0 x
(如果有人能为这种类型的输入参数写出英文专有名称,我将不胜感激。
我的 if
语句应该检查输入的参数是否不是数字:
if(atof(argv[cnt]) == 0 && argv[cnt] != "0")
但不幸的是,当 argb[cnt] = 0 时它是真的(用 GDB 核实)
我做错了什么以及如何解决?
您可以在 C strtol(3) (or strtod(3) 中使用 double
-s) 来管理结束指针:
char* end = NULL;
long n = strtol(argv[cnt], 0, &end);
if (n > 0 && *end == '[=10=]')
printf("got a good number %ld\n", n);
您也可以使用 sscanf(3) 和 %n
。请注意,它正在返回扫描的项目数:
int p= -1;
long n = 0;
if (sscanf(argv[cnt], "%ld %n", &n, &p) >= 1 && p>0)
printf("got a good number %ld (and scanned %d bytes)", n, p);
顺便说一句,如果你需要比较字符串,使用strcmp(3). argv[cnt] != "0"
is comparing addresses and I'm sure on your (or mine) system it would be always true (even for a 0
program argument) since program arguments are in the call stack, but literal strings are in the code segment。
如果您在 C++11 learn about std::string (its operator == do what you imagine) and perhaps std::istringstream
中编码
不要忘记使用所有警告和调试信息进行编译 (gcc -Wall -Wextra -g
),然后 使用调试器 (gdb
)。
PS。我希望你在 Linux,这是一个非常好的学习编程的平台。
我的程序中有这个 if
语句,它应该检查启动程序时输入的参数。例如./a.out 2 2 + 0 x
(如果有人能为这种类型的输入参数写出英文专有名称,我将不胜感激。
我的 if
语句应该检查输入的参数是否不是数字:
if(atof(argv[cnt]) == 0 && argv[cnt] != "0")
但不幸的是,当 argb[cnt] = 0 时它是真的(用 GDB 核实) 我做错了什么以及如何解决?
您可以在 C strtol(3) (or strtod(3) 中使用 double
-s) 来管理结束指针:
char* end = NULL;
long n = strtol(argv[cnt], 0, &end);
if (n > 0 && *end == '[=10=]')
printf("got a good number %ld\n", n);
您也可以使用 sscanf(3) 和 %n
。请注意,它正在返回扫描的项目数:
int p= -1;
long n = 0;
if (sscanf(argv[cnt], "%ld %n", &n, &p) >= 1 && p>0)
printf("got a good number %ld (and scanned %d bytes)", n, p);
顺便说一句,如果你需要比较字符串,使用strcmp(3). argv[cnt] != "0"
is comparing addresses and I'm sure on your (or mine) system it would be always true (even for a 0
program argument) since program arguments are in the call stack, but literal strings are in the code segment。
如果您在 C++11 learn about std::string (its operator == do what you imagine) and perhaps std::istringstream
中编码不要忘记使用所有警告和调试信息进行编译 (gcc -Wall -Wextra -g
),然后 使用调试器 (gdb
)。
PS。我希望你在 Linux,这是一个非常好的学习编程的平台。