我是编码和C语言的新手,我不知道如何使用命令行参数来查看它们是否为int以及是否为真,请继续使用它们。
我已经尝试过使用sscanf,但是我不确定如何使用它来检查参数是否为整数。
#include<stdlib.h>
#include<stdio.h>
#define MAX_SIZE 100
int main(int argc, char* argv[]) {
int status;
char ch;
status = sscanf(argv[1], "%d%c", &n, &ch);
if(status==1){
printf("argument is %d", argv[1]); //to see whats arg 1
}
else {
// if they're not int
printf("Usage: Subset n k (n and k are ints)");
}
return EXIT_SUCCESS;
}
我想看看是否可以打印出参数,但是如果输入一个或多个整数,它会给我一个像“ -432743335”的数字。 如果我输入的不是整数,则会得到使用情况信息,因此可以正常工作 如果没有参数,则会出现分段错误:11
答案 0 :(得分:0)
不要忽略警告:
foo.c:14:31: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘char *’ [-Wformat=]
14 | printf("argument is %d", argv[1]); //to see whats arg 1
| ~^ ~~~~~~~
| | |
| int char *
| %s
要么将参数显示为带有%s
的字符串,要么将已解析的整数显示为带有%d
的整数(如此处所示):
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char* argv[]) {
int status;
int n;
char ch;
status = sscanf(argv[1], "%d%c", &n, &ch);
if(status==1){
printf("argument is %d", n);
}
else {
printf("Usage: Subset n k (n and k are ints)");
}
return EXIT_SUCCESS;
}
为避免在不输入参数的情况下崩溃,请检查argc
(参数数量)是否至少为2。
答案 1 :(得分:0)
您非常接近,似乎您对几个变量感到困惑。当您尝试将n
转换为sscanf
时,第一个&n
不会在任何地方声明,导致 Undefined Behavior 。 (您的编译器应该向您尖叫警告和错误-上面的代码不应编译)
不需要ch
。而是循环遍历1 -> argc
中的所有参数(argv[0]
始终是正在运行的程序名称)。您正在执行出色的工作 验证sscanf
的退货-这是正确的编码。您可以简单地使用状态标志(任何int
变量都可以),如果遇到非整数,只需设置标志TRUE
(例如,将其设置为非零的任何值)即可,遍历所有参数,然后最后确定是否遇到非整数,例如
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
int main (int argc, char *argv[]) {
int nonint = 0; /* simple status flag, set if non-integer encountered */
for (int i = 1; i < argc; i++) { /* loop over all arguments */
int status, n;
status = sscanf (argv[i], "%d", &n); /* attempt conversion */
if (status == 1) /* validate return */
printf ("argument[%d] is %d\n", i, n); /* output int argument */
else { /* otherwise handle error & set nonint flag = TRUE */
printf ("argument[%d] non-integer argument: %s.\n", i, argv[i]);
nonint = 1;
}
}
if (nonint) { /* if nonint flag set, show usage */
fputs ("\nUsage: Subset n k (n and k are ints)\n", stderr);
exit (EXIT_FAILURE);
}
return EXIT_SUCCESS;
}
使用/输出示例
如果存在非整数参数,则在上方设置nonint
标志,在识别非整数参数后显示用法,并返回EXIT_FAILURE
:
$ ./bin/cliargs 1 2 3 four 5 six 7
argument[1] is 1
argument[2] is 2
argument[3] is 3
argument[4] non-integer argument: four.
argument[5] is 5
argument[6] non-integer argument: six.
argument[7] is 7
Usage: Subset n k (n and k are ints)
验证退货:
$ echo $?
1
如果所有参数都是整数,则不显示用法,并且返回EXIT_SUCCESS
:
$ ./bin/cliargs 1 2 3 4 5 6 7
argument[1] is 1
argument[2] is 2
argument[3] is 3
argument[4] is 4
argument[5] is 5
argument[6] is 6
argument[7] is 7
验证退货:
$ echo $?
0
仔细检查一下,如果还有其他问题,请告诉我。