c - scanf 导致无限循环并且不返回 -1 或 EOF

标签 c scanf infinite-loop

我的程序应该从标准输入读取整数,然后

例子:

输入文件包含:"3 1 4 2 5\n"
函数输出:"{3, 1, 4, 2, 5}\n"

输入文件包含:"1 2 3 4 5 6 7 8\n"
函数输出:"{1, 2, 3, 4, 5, 6, 7, 8}\n"

输入文件包含:无(空文件)
函数输出:“未提供整数。\n”

在我尝试使用如下所示的 .txt 文件从标准输入重定向中读取之前,这对普通标准输入工作正常

input .txt file

输入.txt : 1 2 3 4 5 6 7 8 9 10

在运行 GDB 时我看到了这个:

My GDB

它一直用 10 填充我的整数数组,直到我的程序崩溃。

这是我的代码:

#include <stdio.h>

void printNums() {
  int nums[100];
  int num;
  int count = 0;
  int x;
  if ((scanf("%d", &num)) == EOF) {
    printf("No integers were provided.\n");
    return;
  } else {
    nums[count] = num;
    count++;
  }
  while ((scanf("%d", &num) == 1)) {
    if (num != ' ') {
      nums[count] = num;
      count++;
    }
  }
  printf("{");
  for (x = 0; x < count; x++) {
    if (x == count - 1) {
      printf("%c", nums[x]);
    } else {
      printf("%c, ", nums[x]);
    }
  }
  printf("}\n");
}

请记住,我不允许导入除 stdio 以外的任何其他内容,它比用户 scanf 或 getchar 更可取

最佳答案

无限循环的原因在于参数 %d,它是一个带符号的十进制整数,而不是您输入的字符。是的,正如@SteveSummit 注意到的那样,他应该把它作为另一个答案放在这里,使用 %c 将解决问题。我认为,问题的根本原因是在输入 %d 时未使用隐式换行符。 %c 确实关心它。

关于c - scanf 导致无限循环并且不返回 -1 或 EOF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48709024/

相关文章:

c - 使用内存映射或解锁流操作?

C语言: I want to add all the positive integers when a negative number is inserted

c - 此TRIE算法代码在CS50 IDE编译器上运行,但在Windows上的TDM-GCC中进入无限循环

java - 使用 DocumentBuilder 解析 XHTML 时出现无限循环 "parse"

php - PHP echo 语句中的无限递归

c - 接收 SMTP 消息

c - 使用具有固定宽度整数类型变量的 printf 宽度说明符

c - for循环后scanf

c - %ms 和 %s scanf 之间的区别

C 无法输入 scanf