C 在 scanf() 处无限循环

标签 c

我是 C 新手,我检查了一些解决方案,虽然我只能找到字符的东西(并用字符尝试了他们的解决方案),但它不起作用,我想知道为什么我无限循环(也无法输入任何内容)。当我输入例如字母时,我期望的是一个新的输入。

#include <stdio.h>
#pragma warning(disable:4996)

int main(void)
{
  float num1;
  while (!(scanf("%f", &num1)))
   {
     scanf("%f", &num1);
   }
}

最佳答案

  • 当您输入第一个数字时,循环将按预期退出
  • 当你输入一个字符时,scanf将返回0,因为它没有读取到正确的输入(因为scanf返回分配的输入项的数量)。因此它进入了 for 循环,但是当你正确输入数字时,你期望 scanf 返回 1 并退出循环。
    但是之前的输入仍然保留在缓冲区中。
    一种可能的解决方案是


#include <stdio.h>
float get_float_input() {
  // Not portable
  float num1;
  while (!(scanf("%f", &num1))) {
    fseek(stdin, 0,
          SEEK_END); // to move the file pointer to the end of the buffer
  }
  return num1;
}
float get_float_input_func() {
  // Portable way
  float num1;
  int ch;
  char buff[1024];
  while (1) {
    if (fgets(buff, sizeof(buff), stdin) == NULL) {
      while ((ch = getchar()) != '\n' && ch != EOF)
        ; // Clearing the input buffer
      continue;
    }
    if (sscanf(buff, "%f", &num1) != 1) {
      continue;
    }
    break;
  }
  return num1;
}
int main(void) {
  float num1;
  num1 = get_float_input_func();
  printf("%f\n", num1);
  return 0;
}

关于C 在 scanf() 处无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52769374/

相关文章:

c - 如何读取命令行中给出的目录并打开和打印目录

c - 使用 ZeroMQ 和 ProtocolBuffers 发送结构

c - 没有与 GCC 的内存对齐

c - C 中的字符串切片和复制

c - C 的夹板代码分析器

c++ - 如何处理带有 %d 格式说明符的字符?

c - 来自 C 程序的 Gnuplot - 只允许对超过一定长度的文件进行绘图

c - C中具有精确长度的字符串的快速字符串比较

c - 为什么这个CPU运行速度更快?

c - C 中的指针转换和 "free"