简体   繁体   English

C在scanf()处无限循环

[英]C loops infinitely at scanf()

I'm new to C and I've checked for some solutions, though I can only find stuff for chars (and tried their solutions with chars), it didn't work aswell, I want to know why I'm infinitely looping (Can't input anything aswell). 我是C语言的新手,我已经检查了一些解决方案,尽管我只能找到char的东西(并尝试使用chars解决方案),但它也无法正常工作,我想知道为什么我无限循环(无法输入任何内容)。 What I expect is a new input when I enter for example a letter. 我希望输入的是例如字母的新输入。

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

int main(void)
{
  float num1;
  while (!(scanf("%f", &num1)))
   {
     scanf("%f", &num1);
   }
}
  • When you enter the first input as a number, the loop exits as expected 当您以数字形式输入第一个输入时,循环将按预期方式退出
  • When you enter a character, scanf will returns 0 since it has not read a correct input(since scanf returns the number of input items assigned). 输入字符时,scanf将返回0,因为它尚未读取正确的输入(因为scanf返回分配的输入项数)。 Thus it enters the for loop, but when you enter the number correctly you expect the scanf to return 1 and exit the loop. 因此它进入for循环,但是当您正确输入数字时,您期望scanf返回1并退出循环。
    But the previous input is still remains in the buffer. 但是以前的输入仍然保留在缓冲区中。
    One possible solution is 一种可能的解决方案是


#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM