C++ Console Input


One of the most common methods of entering data into a program is to read typed character input from a keyboard. Such input is often referred to as "console input", named after early computer consoles (video terminals). The C++ language implements console input using stream objects such as cin, which can be used to represent a stream of character data coming into a program from a device such as a keyboard. It is used in combination with the stream extraction operator >> to feed keyed-in data into one or more variables. The second statement in the source code segment below handles the transfer of the keyed-in data into a variable named PRICE:

   cout << "What is the price? ";   // Prompt the user for the correct data
   cin >> PRICE;                    // Read the keyboard input buffer in to PRICE

Notice that the first statement above, which displays the prompt (the message urging the user to act), does not include any characters that cause the cursor to advance to a new line on the screen. This is done to ensure that the echo of the user's keystrokes (performed during entry of the data) appears on the same line as the prompt. If the entry is expected to involve a large string of characters, then an endl stream manipulator or a '\n' escape sequence should be added to the end of the prompt (as shown below) to cause the cursor to advance to the line below the prompt. This allows the width of the entire line to be used for the input data.

   cout << "What is the price?\n";   // Prompt the user for the correct data and advance a line
   cin >> PRICE;                     // Read the keyboard input buffer in to PRICE

Regardless of whether a new line is executed after the prompt or not, the cin object always outputs a new line character after the user presses the Enter key to complete an input step.

How cin Works

The cin streaming object is used primarily to read characters from a computer's keyboard buffer. This area of memory is used as a "waiting room" for keystrokes. User keystrokes are stored in this buffer automatically by the operating system as keys are pressed. This includes the new line character \n generated when the Enter key is pressed. The keyboard buffer can be read using stream objects such as cin. As the buffer is read (character by character), the operating system keeps track of the address of the last character read from the buffer, so that sebsequent reads of the buffer will pickup with the next keystroke. The cin streaming object determines how many characters to read from the buffer in order to transfer the appropriate data into each variable listed in the input statement. For example, a char variable would receive only a single keystroke from the buffer. Alternatively, a string variable would receive characters from the buffer until the \n (new line) character was encountered, which would remain in the buffer and not be stored in the string variable. Whenever cin encounters a blank space or any other whitespace character (including \n) at the start of a keyboard buffer during a read operation, it just skips ahead to the next non-whitespace character and continues reading. This approach allows us to read keyed input into multiple variables by separating their data using one or more whitespace characters when entering it. For example, a program could request a store three test scores using the following source code:

float S1, S2, S3;  // Three test scores
cout << "Enter three test scores (separated by spaces):";
cin >> S1 >> S2 >> S3;

A user response to the input statement above could be

70[Enter]
80[Enter]
90[Enter]

or

70[Space]80[Space]90[Enter]

or

70[Tab]80[Enter]
90[Enter]

All of the responses above would result in variables S1, S2, and S3 receiving the values 70, 80, and 90 respectively.

The use of whitepace characters as item delimiters by the cin object makes it difficult to read strings of characters that contain literal whitespace characters. To allow this, C++ contains a function named getline that treats whitespace characters as literal parts of string input rather than delimiters. The getline function is used in combination with the cin object as in the simple sample program below:

#include <iostream>
#include <string>
using namespace std;
int main(void)
{
string FULLNAME;  // Variable intended to hold multiple words separated by spaces
cout << "What is your full name ? ";
getline(cin,FULLNAME);
cout << "Hi " << FULLNAME << endl;
return 0;
}

Notice the extra compiler directive to include the string header file to allow the definition of string objects in the program. The getline function processes all keystrokes in the keyboard input buffer, including all whitespace characters except for \n (which terminates the input string), and stores them in the string variable specified as the second parenthesized argument for the function. A third optional argument can be included to specify a delimiter (other than the default '\n') to signal the end the input. Beware that when you specify a delimiter other than '\n' in the getline function, any '\n' entered in the input would be stored just like any other character in the input buffer and would not terminate the input of the string.

NOTE: The getline function should not be confused with the getline member function of the cin object, which is used to input C-strings. If you want information about this, read Chapter 10 and the pages about C-strings on this site.

For information about other techniques for inputting literal whitespace characters, read the web page entitled Console Input of Character Data in C++.

Keyboard Entry of Numeric Data

Numeric data is entered at the keyboard as numerals (and possibly a dash to represent a minus sign and a dot to represent a decimal point). When numerals are read from the buffer, cin converts the non-whitespace keystrokes read from the buffer into the numeric type of data expected by the receiving variable and stores the data in the data language matching that variable's data type (int, float, double, etc.) The terminating \n character remains unprocessed in the buffer because it is not a character that is involved in the variable's numeric data. Unprocessed \n characters are not a problem if the next input statement is one like cin that skips leading whitespace during input. For information about other techniques for inputting literal whitespace characters, read the web page entitled Console Input of Character Data in C++.

PATH: Instructional Server> COP 2000> Examples>