Skip to the content of the web site.

Lesson 1.14: Console input

Up to this point, we have described how to print characters to the console using the std::cout object together with the left-shift operator <<. We will now see how we can retrieve input from the console input, which by default is the keyboard.

To request data from the keyboard, we use the std::cin object together with the right-shift operator. We must store that entered data somewhere, so we will use a local variable (although, one could use a parameter, too). For example,

// Pre-processor include directives
#include <iostream>

// Function declarations
int main();

// Function definitions
int main() {
    int n;    // No default value
    std::cout << "ENter an integer: ";
    std::cin >> n;

    std::cout << "You entered the integer " << n << std::endl;
     
    return 0;
}

Again, the right-shift operator is used to suggest a direction of flow of information: from the console to the variable. Whatever value the variable n prior to the user entering a number is lost.

Now, timing is important, because the program is attempting to execute code, but it must wait for the user to enter data through the keyboard. Thus, the execution of the program will be suspended until the user types something at the keyboard and presses Enter. When the user presses Enter, the library code will attempt to interpret what was being asked for.

Now, one issue with console input is that the characters that the user entered must be interpreted, and sometimes the interpretations may appear to be bewildering.

Now, the compile will call different interpreters depending on the type of the variable. We will review each of the four types associated with the four primitive types:

Integers

An integer (int or long or any other integer type) must be an optional + or - followed by one or more digits, including the possibility of a leading zero. Thus, if the user inputs [+-]?[0-9]+, that will be interpreted as an integer.

You can try either of these examples at repl.it: repl.it 1 and repl.it 2.

Boolean

A bool must be either 0 or 1. You cannot, for example, enter true or false.

Floating-point numbers

If the type is float or double, then the input must be one of

           [+-]?[0-9]+
           [+-]?[0-9]+\.[0-9]*
           [+-]?[0-9]*\.[0-9]+
           [+-]?[0-9]+[eE][+-]?[0-9]+
	   [+-]?[0-9]+\.[0-9]*[eE][+-]?[0-9]+
	   [+-]?[0-9]*\.[0-9]+[eE][+-]?[0-9]+

If you wish to write this as a single regular expression, you could use

    [+-]?([0-9]+|[+-]?[0-9]+\.[0-9]*|[+-]?[0-9]*\.[0-9]+)([eE][+-]?[0-9]+)?

A number like -2.3e5 is interpreted as $-2.3 \times 10^5$.

Characters

If asked to access a character from the keyboard via

         char ch;     // Uninitialized
         std::cin >> ch;

will find the first non-whitespace character that is entered in the screen. Thus, if at the keyboard, the user enters any of the keys Spacebar, Tab, or Enter, these are ignored.

String

Previously, we saw that a programmer can code a string literal by hard coding the characters between opening and closing double quotes "; for example, "Hello world!". Some characters must be escaped, because otherwise there is no way of entering specific characters (such as the ", the Tab character, a new-line character, a carriage-return character, or a bell (\b).

If you want to accesses a string of characters from the keyboard, we require a type that can store more than one characters. In the standard library, there is a string class, which we will revisit in the future; however, at this point, we will describe its use. The std::string class is defined in the string library.

// Pre-processor include directives
#include <iostream>
#include <string>

// Function declarations
int main();

// Function definitions

// Ask the user to enter a word and then print that word to the screen
int main() {
    std::string str{};

    std::cout << "Enter a word: ";
    std::cin >> str;

    std::cout << "You entered the word \"" << str << "\"."
               << std::endl;

    return 0;
}

If you execute this code, you will see that it ignores all whitespace (spaces, tabs, or Enter) until the first non-whitespace character is found. After this, it continues to include all non-whitespace characters until the next whitespace character.

You can try this at repl.it.

Up to now, the only operations we have performed with strings is to declare one, to store in that string the characters that were entered at the keyboard, and to print it to the screen. Two operations which were perhaps hidden to you was when it string was declared, it was also initialized to be the empty string (a string with zero characters). Also, just before main() returns, it is also necessary to clean up any memory allocated for the string class (after all, the user could enter Antidisestablishmentarianism.

Questions and practice:

1. Does entering text from the keyboard treat the \ in any way special? Use the std::string example to see what happens if you enter "Hey, Sherry said to say 'hi'!". Do you need to escape the " or ' characters? What happens if you enter a spider: /\o/\?