c - 总结命令行

标签 c command-line atoi argc

非常简单,我正在尝试对命令行中输入的所有整数求和。总和实际上有效,如果我以“1 1 1 1 ”输入启动程序,总和将增加四次。问题是 sum 被初始化为某个非常大的数字 (4293283588)。这是为什么?

int main(int argc, char*argv[])
{
  int a = 0;
  int sum = 0;
  size_t i = 0;

  for (i=0; i<argc; i++)
  {
     a = atoi(argv[i]);
     sum = sum + a;
     printf("%ld\n", sum);
  }

  return 0;
}

最佳答案

argv[0] 可能是可执行文件的名称。来自标准:

5.1.2.2.1 Program startup

....

If the value of argc is greater than zero, the string pointed to by argv[0] represents the program name; argv[0][0] shall be the null character if the program name is not available from the host environment. If the value of argc is greater than one, the strings pointed to by argv[1]
through argv[argc-1] represent the program parameters.

尝试

for (i=1; i<argc; i++)

此外,正如 @BLUEPIXY 指出的那样,%ld 假定类型为 long。因此,要么将其更改为 %d,要么使用 long sum

关于c - 总结命令行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26090997/

相关文章:

c - 在 Mac OS X 和 Ubuntu 中对 C 使用 atoi() 时的不同结果

c - 关于使用 unicode 输入和文件输出改进代码的问题

mysql - 用户可以通过 PDO 连接,但不能通过 C mysql_real_connect 连接

node.js - 在 node.js 中获取原始命令行参数

mysql - 存储过程/函数列表 Mysql 命令行

c - C语言中将字符转换为字符串的API

c - 在C中如何将字符串的一部分转换为int?

c - 如何使用 minilibx 进行编译?

python - 从 api 模拟多行 shell 行为

ruby - 在命令行上将选项传递给 Haml