+ 1
[C] Scanf statement ignored in do while loop until first round
Why is the scanf statement here ignored unless i put another scanf statement after it or until after the condition has been confirmed once. This happened even when I seperated the initial printf and scanf statements from the loop and used a while loop instead. choice = (char) 'Y'; do { printf ("\n\nIs there a 90 degree angle? (Y/N): "); scanf ("%c", &choice); } while (choice != 'Y' && choice != 'y' && choice != 'N' && choice != 'n'); https://code.sololearn.com/c596jjvt0RUj/?ref=app
1 Réponse
+ 4
I see at line 19, an integer variable called `choice` has been declared, then to the same variable at line 32 (which is a subscope relative to the scope of `choice`) a character value (with unnecessary casting) being assigned. As far as the compilation and implicit type conversion are concerned, the program reaches smoothly to that point without any interruption, nevertheless, I can't see any convincing reason why a clean and compatible local declaration like
char yes_no = 'Y';
hasn't been made at line 32. Similarly, the implementation of `InvalidYN ()` is full of implicit promotions to `int` that can be easily eliminated.
As for notorious `scanf()`, the carriage return character (`\n`) when hitting the Enter key causes such bizarre behavior. Indeed the best course of treatment would involve replacing the `scanf()` with a more reliable function as mentioned and separately discussed by Gordie and others, however, we still can make use of some simple tricks to get over the problem "rudimentarily". It'd a simple separate function responsible solely for discarding any leftover from the input buffer like this
void clbuf() {
int c;
while ( ( c = getchar() ) != '\n' && c != EOF )
;
};
It can be called after each `scanf()` for making sure everything is good to go for the rest of the iterations.
Live demo: https://rextester.com/MNT41396