簡體   English   中英

C在scanf()處無限循環

[英]C loops infinitely at scanf()

我是C語言的新手,我已經檢查了一些解決方案,盡管我只能找到char的東西(並嘗試使用chars解決方案),但它也無法正常工作,我想知道為什么我無限循環(無法輸入任何內容)。 我希望輸入的是例如字母的新輸入。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM