Reputation: 194
Let's say I am writing this piece of code:
char c; // c from choise.
do{
printf("Please choose one of the following operators:\n");
printf("+ for Addition\n- for Subtraction\n* for Multiplication\n/ for Division\n");
printf("= for Assignment and\nE to check if two variables have the same type and value.\n");
scanf("%c", &c);
}while(c!='+' && c!='-' && c!='*' && c!='/' && c!='=' && c!='E');
The main problem is, when the user inserts numbers or letters, everything else other than the above operators, each message inside the printf appears twice on the screen.
For example, if c='A' we have:
Please choose one of the following operators:
+ for Addition
- for Subtraction
* for Multiplication
/ for Division
= for Assignment and
E to check if two variables have the same type and value.
A //wrong answer, the loop continues...
Please choose one of the following operators:
+ for Addition
- for Subtraction
* for Multiplication
/ for Division
= for Assignment and
E to check if two variables have the same type and value.
Please choose one of the following operators:
+ for Addition
- for Subtraction
* for Multiplication
/ for Division
= for Assignment and
E to check if two variables have the same type and value.
//here the program awaits the new value of c.
But, if c='-' or c='+' etc., of course we have
Please choose one of the following operators:
+ for Addition
- for Subtraction
* for Multiplication
/ for Division
= for Assignment and
E to check if two variables have the same type and value.
- // or +
//the program goes to the next line.
Same thing happened when I tried to convert the do_while loop in the while or for loop.
Upvotes: 0
Views: 122
Reputation: 4023
Add a space before %c
: scanf(" %c", &c);
. This is because the newline entered from previous input might get stored in c
.
You can also clear the input buffer using a getchar()
after the scanf()
.
Upvotes: 0
Reputation: 16540
After the user types an incorrect character, there is still (at least) a newline in the stdin buffer.
The comment by @haccks is one way to fix the problem. Another way is to follow the scanf by a short loop that calls getchar until EOF is received.
Upvotes: 0