|
||||
|
« Things to Avoid in C/C++ -- scanf, Part 5 | Things to Avoid in C/C++ -- scanf / string, Part 7 » |
Things to Avoid in C/C++ -- scanf / character, Part 6
by: WaltP - Sep 26, 2005
scanf() / Reading a characterTwo of the biggest drawbacks to scanf() and reading a single character is:
One of the problems with either function is that it reads 1 character, but the keyboard input has more than one character in it. If you enter a for a character input, you actually have two characters, the a followed by the \n. Both functions will leave the \n in the buffer for the next read so it's up to you to read off the rest of the characters so you have a clean buffer for the next read. Compare these two code segments that alleviate this problem: C/CPP/C++ Code Example: char c; // using getchar() c = getchar(); while (getchar() != '\n'); // using scanf() scanf("%c", &c); while (scanf("%c") != '\n'); With scanf(), it has to process The Steps multiple times. What if you entered abcdef? So for reading a character, scanf() is like a pile-driver when all you needed was a hammer. So use getchar() instead. It's easier and designed exactly for the task at hand. Just remember to clear the keyboard buffer. In either case, the trailing \n will be left in the input stream. Next up: scanf() / Reading a string. So stay tuned...
|
GIDNetwork Sites
Archives
Recent GIDBlog Posts
Recent GIDForums Posts
Contact Us
|
« Things to Avoid in C/C++ -- scanf, Part 5 | Things to Avoid in C/C++ -- scanf / string, Part 7 » |