在获取之前输入C. Scanf.问题

Dmi*_*tri 10 c gets input scanf

我是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;
}
Run Code Online (Sandbox Code Playgroud)

它允许输入ID,但它只是跳过其余的输入.如果我改变这样的顺序:

printf("Input your name: ");
   gets(b);   

   printf("Input your ID: ");
   scanf("%d", &a);
Run Code Online (Sandbox Code Playgroud)

它会工作.虽然,我不能改变秩序,我需要它原样.有人能帮我吗 ?也许我需要使用其他一些功能.谢谢!

IVl*_*lad 12

尝试:

scanf("%d\n", &a);
Run Code Online (Sandbox Code Playgroud)

获取只读取scanf离开的'\n'.另外,你应该使用fgets not gets:http://www.cplusplus.com/reference/clibrary/cstdio/fgets/以避免可能的缓冲区溢出.

编辑:

如果上述方法不起作用,请尝试:

...
scanf("%d", &a);
getc(stdin);
...
Run Code Online (Sandbox Code Playgroud)


And*_*Dog 7

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
Run Code Online (Sandbox Code Playgroud)