![]() |
||||
|
||||
|
« Installing Borland's Command Line Compiler | Things to Avoid in C/C++ -- void main(), Part 10 » |
Reading a Single Character
by: WaltP - Oct 10, 2005
C / C++ buffers its input which means a RETURN must be entered to get standard input functions to continue. This RETURN is actually added to the input stream, which will cause character inputs to malfunction. Here is a function you can use to read any single, non-whitespace character. This would be used in place of scanf("%c", &ch) or ch = getchar() to make sure you actually get to input the value: C/CPP/C++ Code Example: int getCharacter() { int ch; // define the character do // loop until a good character is read { ch = getchar(); // read a character } while ( (ch == 0x20) || // check for SPACE ((ch >= 0x09) && (ch <= 0x0D)) // check for the other whitespace ); return ch; } This will keep reading until there is a non-whitespace character entered, effectively clearing the buffer from previous inputs. Whitespace is defined as the following characters: Generic Code Example: Hex Dec Ctrl Name 0x09 9 ^I Tab 0x0A 10 ^J Line Feed 0x0B 11 ^K Verticle Feed 0x0C 12 ^L Form Feed 0x0D 13 ^M Carriage Return 0x20 32 Space This function will accept only printable non-whitespace: C/CPP/C++ Code Example: int getCharacter() { int ch; // define the character do // loop until a good character is read { ch = getchar(); // read a character } while ((ch <= 0x20) || // check above SPACE (ch >= 0x7F) // check below the last ASCII char ); return ch; } This is a more usable function because it also ignores the control characters.
|
GIDNetwork Sites
Archives
Recent GIDBlog Posts
Recent GIDForums Posts
Contact Us
|
« Installing Borland's Command Line Compiler | Things to Avoid in C/C++ -- void main(), Part 10 » |