Why does funciton get not working and skip user input?

#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
    char aa[35];
    int a;
    scanf("%d",&a);
    gets(aa);
    puts(aa);
}

It does not accept a string from the user, but if I take a string before an integer value, it works fine.

+4
source share
4 answers

Once it scanf("%d",&a);displays the numeric characters from stdinto form intfor a, this is done. He does not consume '\n', which can follow him.

gets(aa);consumes data before '\n'.

Thus, input similar 1 2 3 x y Enterto will add 123in aand "xy"in aa.

scanf("%d",&a);
gets(aa);

Input similar to the 4 5 6 Enterabove will put 456in aand ""in aa.


fgets() .

if (fgets(aa, sizeof aa, stdin) == NULL) Handle_EOF();
if (sscanf(aa, "%d", &a) != 1) Handle_Nonnumeric_Input();

if (fgets(aa, sizeof aa, stdin) == NULL) Handle_EOF();
aa[strcspn(aa, "\n")] = '\0'; // truncate potential \n
0

get():

gets(aa);
gets(aa);
0

, u Google IO , , , pres "Enter", , "\n" , - , IO, 2 Flush(stdin); _flushall();

0

fflush scanf . .

#include<stdio.h>
void main()
{
    char aa[20];     
    int b;
    scanf("%d",&b);
    fflush(stdin);
    gets(aa);
    puts(aa); 
    getchar();
}

gets(), .

-1

Source: https://habr.com/ru/post/1628771/


All Articles