Hi Just started learning c for uni (usually use objective c) and have run into a strange issue with scanf, i have the following code
while(stringCheck == 0){
scanf("%c",&computerType);
computerType = toupper(computerType);
if ( computerType == 'L') {
/*set stringCheck to 1 so the scanf while loop breaks*/
stringCheck = 1;
counter = 0;
} else {
printf("ERROR\n");
}
}
开发者_如何学Go
This i printing out "ERROR" then asking for input (so it is skipping the scanf statment the first time). If i change the it to another variable that is a string it works fine, it stops on the first time.
The rest of the code works fine, its just the fact that it print an error as soon as it enters the loop that is annoying.
I have tried getChar()
and it does the same thing.
Thank you for any help you have to offer.
If it's printing an error the first time you enter the loop, then there's already something in the input buffer. I'll guarantee (assuming your compiler is not brain-dead) that it is not skipping the scanf
. You should check what it's actually receiving by changing:
printf("ERROR\n");
to:
printf("ERROR, code = %02x\n", computerType);
I would suggest that it's the newline from the last time your program ran that code (you say it's the first time but it's unclear as to whether you mean the first time into that loop ever (since program started) or first time entering that loop but you've been through it before on this program run.
When you enter LENTER the first time, your code will pull out the L
but not the ENTER
. If you then call that code again, it will get the ENTER
key.
You should either understand and allow for what's actually entered or use a safe and sound input function like this one.
You should always check the return value from scanf()
; it tells you how many of the conversions succeeded. In this context, if you don't get back 1, you have a problem. The first time around the loop, scanf()
reads a character - but not an ell (l
or L
) because you say you get an error message. The next iteration attempts to read the newline or whatever else follows the previous erroneous character, and the newline is certainly not an ell, and the other characters quite likely aren't an ell either, thus producing at least one more error message. You would get an error printed for each non-ell character.
Generally, if you use scanf()
, it is fairly hard to recover from errors. You're likely to be better off reading a line into a buffer (character array) and use sscanf()
to parse it.
You should just need to add a space before %c
. I am unsure why it works, but it does. This also happens with other data types.
Replace your scanf
statement with scanf(" %c",&computerType);
精彩评论