【问题标题】:How to get integer input in an array using scanf in C?如何在C中使用scanf获取数组中的整数输入?
【发布时间】:2020-04-04 07:45:44
【问题描述】:

我正在使用 scanf 获取多个整数输入并将其保存在数组中

while(scanf("%d",&array[i++])==1);

输入的整数用空格分隔,例如:

12 345 132 123

我在另一篇文章中阅读了此解决方案。

但问题是 while 循环没有终止。

这句话有什么问题?

【问题讨论】:

  • 输入EOFctrl + zctrl + d)并输入
  • @BLUEPIXY 是否可以在不使用 EOF 的情况下做到这一点?例如使用该程序的新用户不添加EOF?还有没有其他方法可以避免使用EOF(可能不使用'while')
  • 这样输入12 345 132 123..作为输入结束标记。(scanf输入失败)

标签: c scanf


【解决方案1】:

OP 使用 Enter'\n' 来指示输入的结尾,并使用空格作为数字分隔符。 scanf("%d",... 不区分这些空格。在 OP 的 while() 循环中,scanf() 消耗 '\n' 等待额外的输入。

改为使用fgets() 读取一行,然后使用sscanf()strtol() 等进行处理。 (strtol() 最好,但 OP 使用的是scanf() 家庭)

char buf[100];
if (fgets(buf, sizeof buf, stdin) != NULL) {
  char *p = buf;
  int n;
  while (sscanf(p, "%d %n", &array[i], &n) == 1) {
     ; // do something with array[i]
     i++;  // Increment after success @BLUEPIXY
     p += n;
  }
  if (*p != '\0') HandleLeftOverNonNumericInput();
}

【讨论】:

    【解决方案2】:
    //Better do it in this way
    int main()
    {
      int number,array[20],i=0;
      scanf("%d",&number);//Number of scanfs
      while(i<number)
      scanf("%d",&array[i++]);
      return 0;
    }
    

    【讨论】:

    • number 需要在 while 循环 I.E 中使用。 while( i
    【解决方案3】:

    你应该试着这样写你的陈述:

    while ( ( scanf("%d",&array[i++] ) != -1 ) && ( i < n ) ) { ... }
    

    请注意边界检查。

    正如人们一直说的那样,在解析来自普通人类的真实输入时,scanf 不是你的朋友。它在处理错误情况时有很多陷阱。

    另见:

    【讨论】:

    • 即使这段代码在不使用 EOF 的情况下也会陷入无限循环
    【解决方案4】:

    您的代码没有任何问题。并且只要输入的整数个数不超过数组的大小,程序就会一直运行,直到输入 EOF。即以下作品:

    int main(void)
    {
        int array[20] = {0};
        int i=0;
        while(scanf("%d", &array[i++]) == 1);
        return 0;   
    }  
    

    正如 BLUEPIXY 所说,您必须为 EOF 输入正确的击键。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-11
      • 2015-11-26
      • 2018-05-11
      • 1970-01-01
      • 1970-01-01
      • 2017-12-01
      相关资源
      最近更新 更多