While loop

I was wondering why in my determine_teacher function the printf call executes twice every time I enter an invalid character?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
  #include<stdio.h> /* for printf and scanf */
 
 /* Macro constants */
 #define UNDER_HUN_DISC .10
 #define OVER_HUN_DISC .12
 #define TAX_RATE .05
 
 /* function prototypes */
 int determine_teacher(char user_response); /* prompt user for total and if teacher */
 
 double calculate_discount(double sale_total); /* if teacher, calculate the discount */
 
 /* program entry point */
 int main(void)
 {
 	/* variable dclarations */
 	char teacher_response; /* input, response from user if teacher */
 	double purchase_total; /* input, stores sales total */
 	
 	int teacher; /* store customer status 0(false) not teacher 1(true) teacher */
 	double discount_amount; /* if customer is a teacher stores the discount amount */
 	double discounted_total; /* purchase total minus discount amount */
 	double tax_total; /* stores the total of the sales tax */
 	double trans_total; /* transaction total */
 	
 	/* prompt user for input */
 	printf("Is customer a teacher(Y/N)?");
 	scanf("%c", &teacher_response);

 	teacher = determine_teacher(teacher_response);
 	
 	if(teacher)
 	{
 		printf("Teacher");
 	}
 	else
 	{
 		printf("Not Teacher");
 	}
 	
 	
 	
 }/* end of main() */
 
 /* function that prompts user for input and return if teacher or not */
 int determine_teacher(char input_response)
 {
 	 while(!(input_response == 'Y' || input_response == 'N' || input_response == 'n' || input_response == 'y'))
 	 {
 	 	printf("invalid");
 	 	scanf("%c", &input_response);
 	 }
 	 switch(input_response)
 	 {
 	 	case 'Y':
 	 	case 'y':
 	 		return 1;
 	 	case 'N':
 	 	case 'n':
 	 		return 0;
 	 }
			 	
 }/* end of determine_teacher() */
It looks like when execution reaches line 51, scanf reads the newline character from the previous input.

You could either clear the input buffer before proceeding: while ((ch = getchar()) != '\n' && ch != EOF);

Or, add a space before the %c in the scanf call on line 51. That will make scanf ignore all leading whitespace (including any newline characters). I'm unsure if it will skip carriage return '\r', though.
Topic archived. No new replies allowed.