Help with C scanf syntax

When I run the next snippet, it starts before the second question. Then he puts “Is the client a student? (Y / n) \ n” and “What time of videos (in hours) \ n” appears together (there is no zone for an answer between them). If someone takes any action, the program stops working. What have I done wrong? (I'm sure this is due to the syntax)

int A,B,C,D,age,time;
char edu, ddd;

printf ("What is the customer age? \n");
scanf("%d", &age);

printf ("Is the customer a student? (y/n) \n");
scanf("%c", &edu);

printf ("What is the movies time? (in hours) \n");
scanf("%d", &time);

printf ("Is the movie 3-D? (y/n) \n");
scanf("%c", &ddd);
+3
source share
6 answers

You will probably need to have additional input from stdin after each scan so that it does not stick in the buffer and force scanf to receive buffered data.

, , "% c" - "edu", .

+4

scanf, , , , scanf, , , , .

fgets , , , sscanf.

scanf("%c%*c",&edu);. %*c .

+4

% c. , , , . , - "10\n" , scanf 10. % c . scanf .

printf ("What is the customer age? \n");
scanf("%d", &age);

printf ("Is the customer a student? (y/n) \n");
scanf(" %c", &edu);

printf ("What is the movies time? (in hours) \n");
scanf("%d", &time);

printf ("Is the movie 3-D? (y/n) \n");
scanf(" %c", &ddd);
+2

scanf "% c", . : @jamesdlin. "time" - C-Standard-Lib, , :

int A,B,C,D,age=0,timevar=0;
char edu=0, ddd=0, line[40];

printf ("What is the customer age? \n");
if( fgets(line,40,stdin) && 1!=sscanf(line,"%d", &age) ) age=0;

printf ("Is the customer a student? (y/n) \n");
if( fgets(line,40,stdin) && 1!=sscanf(line,"%c", &edu) ) edu=0;

printf ("What is the movies time? (in hours) \n");
if( fgets(line,40,stdin) && 1!=sscanf(line,"%d", &timevar) ) timevar=0;

printf ("Is the movie 3-D? (y/n) \n");
if( fgets(line,40,stdin) && 1!=sscanf(line,"%c", &ddd) ) ddd=0;

vars , 0 ,!= 0 .

+2

fflush (stdin);

stdin

scanf scanf.

+1

, , , enter, scanf (.. & edu) . , buffer scanf , "Enter".

scanf(" %c", &variable);

( scanf ).

0

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


All Articles