C語言中,如果`scanf()`之後跟著`fgets()`/`gets()`/`scanf()`,會出現什麼問題


問題描述瞭如果`scanf`後面跟著`fgets()`/`gets()`/`scanf()`,程式的執行結果或輸出。

`fgets()`/`gets()` 後跟 `scanf()`

示例

 線上演示

#include<stdio.h>
int main() {
   int x;
   char str[100];
   scanf("%d", &x);
   fgets(str, 100, stdin);
   printf("x = %d, str = %s", x, str);
   return 0;
}

輸出

Input:
30
String
Output:
x = 30, str =

解釋

`fgets()`和`gets()`用於在執行時從使用者獲取字串輸入。在上面的程式碼中,當我們輸入整數後,它不會獲取字串值,因為我們在整數後輸入了換行符,`fgets()`或`gets()`會將換行符作為輸入,而不是預期的“String”輸入。

`scanf()` 後跟 `scanf()`

為了重複使用`scanf()`後跟`scanf()`,我們可以使用迴圈。

示例

 線上演示

#include<stdio.h>
int main() {
   int a;
   printf("enter q to quit");
   do {
      printf("
enter a character and q to exit");       scanf("%c", &a);       printf("%c
", a);    }while (a != ‘q’);    return 0; }

輸出

Input:
abq
Output:
enter q to quit
enter a character and q to exita
a
enter a character and q to exit
enter a character and q to exitb
b
enter a character and q to exit
enter a character and q to exitq

解釋

在這裡,我們看到在額外的換行符後,還有一行額外的“輸入字元並輸入q退出”,這是因為每次`scanf()`都會在緩衝區中留下一個換行符,而下一個`scanf()`會讀取它。解決這個問題的方法是用`scanf()`中的型別說明符使用`%c`,例如`scanf("%c");`,或者使用額外的`getchar()`或`scanf()`來讀取額外的換行符。
`

更新於:2019年12月23日

445 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.