我正在学习C编程.我的程序读取与我提供的数字无关的数字.有帮助吗?我在哪里错过了?
#include <stdio.h>
main(int argc, char argv[])
{
int i,sum, digit;
if(argc == 1)
{
printf("\n No arguments specified");
return 0;
}
for(i=1;i<argc;i++)
{
digit = argv[i];
printf("Argument is: %d", digit);
//sum += argv[i];
}
printf("The sum of all numbers is: %d", sum);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Subbu
你main()错了.它应该是:
int main(int argc, char *argv[])
^
|
IMPORTANT!
Run Code Online (Sandbox Code Playgroud)
由于参数向量是字符串指针的数组,而不是字符数组.
然后,您无效地将参数转换为整数,您需要调用eg strtol()或者sscanf()这样做.这种转换是必要的,因为参数作为字符串数组传递给您的程序,并且字符串"42"(例如)在C中与数字非常不同42.
请注意,我提到的两种转换功能都可以检测它们是否失败; 例如,如果用户给你的程序非数字参数,那么检测它是很重要的,而不是继续将它们视为数字.