GIDNetwork > Things to Avoid in C/C++ -- scanf / character, Part 6
Register
« 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 character

Two of the biggest drawbacks to scanf() and reading a single character is:

  1. the amount of work it takes (refer to The Steps). There are a lot of steps to scanf() as you can see. So why not use a function that cuts out most of them and simply

    1. reads a character from the keyboard buffer

    2. returns the character to your program.

    This is exactly what getchar() does. It operates just like scanf() without all the extra processing.

  2. The size of the function itself. Look at the sizes in the previous article. It's 3 or more times larger than getchar().

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...

Would you like to comment? This story has been viewed 160,605 times.
« Things to Avoid in C/C++ -- scanf, Part 5 Things to Avoid in C/C++ -- scanf / string, Part 7 »

__top__

Copyright © GIDNetwork™ 2001 - 2024

Another website by J de Silva

Page generated in : 0.00559 sec.