|
||||
|
« Things to Avoid in C/C++ -- system("pause"), Part 4 | Things to Avoid in C/C++ -- scanf / character, Part 6 » |
Things to Avoid in C/C++ -- scanf, Part 5
by: WaltP - Sep 21, 2005
scanf()Man, where to begin? scanf() is a notoriously ill-behaved function. Half the time it leaves stuff in the input buffer to mess up your next input. If it finds an error in the input stream, it ungraciously leaves the offensive character for the next read. Now, to be fair, the problems we have with this function is usually through:
rather than errors in the coding of the function itself. But the function is so complex that to a new programmer (and probably most veterans) this function is an enigma. scanf() is a
That's how I feel about scanf(). Admittedly, I've never studied the scanf() fully. I've seen some of the format parameters that have been suggested to alleviate a few of the problems, and they are daunting to say the least. So where do you use this function? First and foremost, do not use it for characters and strings. The next two topics explain why. As for numbers, it doesn't really do too bad, and I'll explore that also. But lack of knowledge is what gets most programmers. They want to read a character from the keyboard so they very logically use the format string "%c". Then wonder why the next read is messed up. How are they supposed to know that after the character was read there was a \n left behind? I've rarely (never?) seen documentation explaining that fact, but through experimentation and logical thinking (and a good debugger), one can in fact figure out what's happening. Another problem is that new programmers tend to use this swiss army knife when a simple spoon would suffice. scanf() is a huge function! What scanf() has to do to work is:
That is a lot of work! Keep these steps handy as we continue through this exploration of scanf() function. They will come up again. I will simply refer to them as The Steps. To examine the size of the scanf() function, I built the following programs to check the executable sizes. Basic empty program:
Character input with getchar() (my preferred function)
Character input with scanf()
So as you can see, there is a lot of overhead having functionality you don't need, especially when reading a single character. This will be the topic of scanf()/character. So stay tuned...
|
GIDNetwork Sites
Archives
Recent GIDBlog Posts
Recent GIDForums Posts
Contact Us
|
« Things to Avoid in C/C++ -- system("pause"), Part 4 | Things to Avoid in C/C++ -- scanf / character, Part 6 » |