Thanks, guys! It works perfectly.
Now just to satiate my curiosity, why does the variable accept a blank space as a char when I never hit a space??
Or is it just a formality to leave a blank before the formatting type?
Thanks, guys! It works perfectly.
Now just to satiate my curiosity, why does the variable accept a blank space as a char when I never hit a space??
Or is it just a formality to leave a blank before the formatting type?
It doesn't match a whitespace. Check the scanf documentation. In particular
So a whitespace in the format string means skip whitespace like a new line.Originally Posted by man 3 scanf
@anduril462,
So it's ok if I use it everywhere, right?
Thanks!
Yes...well, it's ok to use everywhere you want to skip over whitespace . Obviously if you don't want to skip whitespace, don't use it.
Note that one single whitespace char in the format string skips all contiguous whitespace if present. Also note that most scanf format specifiers (all numeric specifiers plus %s) automatically skip whitespace so the space in " %d" is redundant, you can just do "%d".
I'm not a big fan of using scanf for user input -- especially single-character input -- for this reason, it's easy to make a small mistake that breaks your program.
A good rule of thumb is to not mix input modes. So character input like getchar() should not be used in conjunction with formatted input like scanf or line-based input like fgets. Note that scanf("%c") -- without the space -- is effectively the same as getchar however.
This is why I typically avoid scanf for user input, except in the simplest of programs. It's too easy to get scanf stuck on bad user input. I prefer reading line-by-line with fgets. Then I can either use strcmp to look for exact strings, or sscanf (the first 's' is because that version scans formatted strings) to parse out values, or do something else all together.
Anyone interested in the updated code?