我希望用户传递两个参数或将其保留为空白。例如:
./program 50 50
or
./program
当我试图用int main(int argc, char *argv[])
, first thing I have done was to change char *argv[]
to int *argv[]
but it did not work. What I want is from the user is just to enter two integers between 0 and 100. So if it is not two integers then it should give an error.
I was sort of thinking to give out an error with types (as I used to program on C#) but whatever I enter, argv1 would be 'char' type all the time.
So what I have done is
for (int i = 0; i <= 100; i++) {
//printf("%d", i);
if (argv[1] == i) {
argcheck++;
printf("1st one %d\n", i);
}
else if (argv[2] == i) {
argcheck++;
printf("2nd one %d\n", i);
}
This does not work as well. Also it gives warning when compiling, but if I change argv
with atoi(argv[1])
for instance, then it gives a Segmentation fault (core dumped) error.
I need a simple way to solve this problem.
EDIT:
So I fixed with atoi()
, the reason why it was giving segmentation fault was because I was trying it with null value when I have no parameter. So I fixed it up by adding an extra cond. But now the problem is if the value is let's say
./program asd asd
Then the output of atoi(argv[1])
would be 0. Is there a way to change this value?
发布于 2018-09-19 10:33:11
不要使用atoi()
也不要使用strtol()
。atoi()
没有错误检查(正如你发现的那样!)并且strtol()
必须使用全局errno
变量进行错误检查,这意味着你必须设置errno
为0,然后调用strtol()
,然后errno
再次检查错误。更好的方法是使用sscanf()
,它还允许您从字符串中解析任何基本类型,而不仅仅是整数,并且它允许您读取花哨的格式(如十六进制)。
例如,要从字符串解析整数“1435”:
if (sscanf (argv[1], "%i", &intvar) != 1) {
fprintf(stderr, "error - not an integer");
}
从字符串中解析单个字符“Z”
if (sscanf (argv[1], "%c", &charvar)!=1) {
fprintf(stderr, "error - not a char");
}
从字符串解析浮点“3.1459”
if (sscanf (argv[1], "%f", &floatvar)!=1) {
fprintf(stderr, "error - not a float");
}
从字符串解析大的无符号十六进制整数“0x332561”
if (sscanf (argv[1], "%xu", &uintvar)!=1) {
fprintf(stderr, "error - not a hex integer");
}
如果您需要更多错误处理,请使用正则表达式库。
发布于 2018-09-19 11:55:42
这样做:
int main(int argc, char*argv[])
{
long a,b;
if (argc > 2)
{
a = strtol(argv[1], NULL, 0);
b = strtol(argv[2], NULL, 0);
printf("%ld %ld", a,b);
}
return 0;
}
https://stackoverflow.com/questions/-100006139
复制相似问题