我对C很陌生,并且在向程序输入数据时遇到问题。我的代码:#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贡献1836条经验 获得超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 关注
- 568 浏览
添加回答
举报
0/150
提交
取消