tags:

views:

99

answers:

4

When I run the following snippet it runs until the second question. It then puts the "Is the customer a student? (y/n) \n" and "What is the movies time? (in hours) \n" prompts together (no area to answer between them). If one takes any action from there on, the program stops working. What did I do wrong? (i'm pretty sure it's syntax related)

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

printf ("What is the customer's 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  A: 

You probably need to eat the extra input from stdin after each scanf so it doesn't stick around in the buffer and cause scanf to receive the buffered data.

This is because the newline from hitting enter after the first text entry stays in the buffer and is a valid entry for the "%c" format - if you look at the value of "edu" you should find it's a newline character.

Matthew Iselin
+2  A: 

You can add a space before the %c. This is necessary because unlike other conversion specifiers, it doesn't skip whitespace. So when the user enters something like "10\n" as the age, the first scanf reads up to the end of 10. Then, the %c reads the newline. The space tells scanf to skip all the current whitespace before reading a character.

printf ("What is the customer's 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);
Matthew Flaschen
+3  A: 

When reading input using scanf, the input is read after the return key is pressed but the newline generated by the return key is not consumed by scanf, which means the next time you read from standard input there will be a newline ready to be read.

One way to avoid is to use fgets to read the input as a string and then extract what you want using sscanf.

Another way to consume the newline would be to scanf("%c%*c",&edu);. The %*c will read the newline from the buffer and discard it.

codaddict
+2  A: 

There are any problems with scanf and "%c", see eg: @jamesdlin. "time" is the name of a C-Standard-Lib function, better you use a different name, eg:

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

printf ("What is the customer's 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;

At the end your vars have a defined content, 0 for an input-error, !=0 otherwise.