我對C很陌生,并且在向程序輸入數(shù)據(jù)時遇到問題。我的代碼:#include <stdio.h>#include <stdlib.h>#include <string.h>int main(void) { int a; char b[20]; printf("Input your ID: "); scanf("%d", &a); printf("Input your name: "); gets(b); printf("---------"); printf("Name: %s", b); system("pause"); return 0;}它允許輸入ID,但只跳過其余的輸入。如果我這樣更改順序:printf("Input your name: "); gets(b); printf("Input your ID: "); scanf("%d", &a);會的。雖然,我無法更改訂單,但我還是需要它。有人能幫我嗎 ?也許我需要使用其他一些功能。謝謝!
3 回答

米脂
TA貢獻(xiàn)1836條經(jīng)驗 獲得超3個贊
scanf不會占用換行符,因此是的天敵fgets。如果沒有好的技巧,請不要將它們放在一起。這兩個選項都將起作用:
// Option 1 - eat the newline
scanf("%d", &a);
getchar(); // reads the newline character
// Option 2 - use fgets, then scan what was read
char tmp[50];
fgets(tmp, 50, stdin);
sscanf(tmp, "%d", &a);
// note that you might have read too many characters at this point and
// must interprete them, too
- 3 回答
- 0 關(guān)注
- 595 瀏覽
添加回答
舉報
0/150
提交
取消