#include <stdio.h> #include <string.h> int main(void) { char message[200]; int ID; printf("\t[Info] 請輸入員工編號:"); scanf("%d", &ID); printf("員工編號:%d",ID); printf("\n 請輸入要傳遞老闆的訊息:" ); fgets(message,sizeof(message),stdin); printf("您傳給老闆的訊息:%s",message); }
執行結果:

網路上查詢後,發現問題如下:
When you read the integer with
scanf("%d"....)
, it does not remove the newline from the input stream. So when you call fgets
later, it reads and finds a newline , i.e. you read a blank line.
To read the next line instead you will need to consume that newline, e.g.
getchar()
as someone else suggested.因為scanf("%d,...")並不讀進換行字元,當您在之後使用fget時,
就會直接讀到一個換行字元,然候就結束了,所以必須先處理掉這個換行字元,
透過getchar()這個method去讀一個字元。
修正後的程式碼如下:
修正後的程式碼如下:
#include <stdio.h> #include <string.h> int main(void) { char message[200]; int ID; printf("\t[Info] 請輸入員工編號:"); scanf("%d", &ID); printf("員工編號:%d",ID); getchar(); printf("\n 請輸入要傳遞老闆的訊息:" ); fgets(message,sizeof(message),stdin); printf("您傳給老闆的訊息:%s",message); }
執行結果:

參考來源:
https://stackoverflow.com/questions/22552166/fgets-not-working-in-c-linux
沒有留言:
張貼留言