Вход в C. 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;
}

Это позволяет вводить идентификатор, но это просто пропускает остальную часть входа. Если я изменяю порядок как это:

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

   printf("Input your ID: ");
   scanf("%d", &a);

Это будет работать. Хотя, я не МОГУ заявка на изменение, и мне нужна она просто как есть. Кто-то может помочь мне? Возможно, я должен использовать некоторые другие функции. Спасибо!

10
задан Dmitri 2 March 2010 в 20:30
поделиться

3 ответа

Try:

scanf("%d\n", &a);

gets читает только '\n', который scanf оставляет внутри. Также следует использовать fgets, а не gets: http://www.cplusplus.com/reference/clibrary/cstdio/fgets/, чтобы избежать возможных переполнений буфера.

Edit:

если вышеописанное не работает, попробуйте:

...
scanf("%d", &a);
getc(stdin);
...
12
ответ дан 3 December 2019 в 17:58
поделиться

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
7
ответ дан 3 December 2019 в 17:58
поделиться
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
        int a;
        char b[20];
        printf("Input your ID: ");
        scanf("%d", &a);
        getchar();
        printf("Input your name: ");
        gets(b);
        printf("---------");
        printf("Name: %s", b);
        return 0;
}



Note: 
  If you use the scanf first and the fgets second, it will give problem only. It will not read the second character for the gets function. 

  If you press enter, after give the input for scanf, that enter character will be consider as a input f or fgets.
1
ответ дан 3 December 2019 в 17:58
поделиться
Другие вопросы по тегам:

Похожие вопросы: