In order to make a program interactive, it is necessary to let it receive information from its user. C++ offers a standard input stream, std::cin, that reads information entered through the keyboard. Like std::cout, it is defined in the <iostream> library.
Firstly, the program needs a place in memory for storing incoming information. Such a storage location is called a variable. When declaring a variable, you specify the data type that it can store and assign the variable a name. For instance, the following declaration reserves space for a whole number representing a person’s age:
int age;
The input stream can then read information and store it in the declared variable. The stream extraction operator, >>, directs data from std::cin into the destination variable:
// Extract formatted input into the target variable
std::cin >> age;
For most formatted value extractions, including extraction into std::string, the stream begins by skipping leading whitespace. It then consumes only the characters that belong to the requested value. For instance, if the available input is 123abc, extracting an integer may succeed with the value 123, while abc remains unread for a later operation. Thus, an input operation does not necessarily require the entire line to match one value.
#include <iostream>
int main()
{
int age;
std::cout << "Enter your age: ";
std::cin >> age;
std::cout << "You are " << age << " years old.\n";
return 0;
}
When the program reaches std::cin >> age;, it waits for the user to enter a value and press the Enter key. The characters entered by the user are read, converted to the required data type, and placed in the age variable.
Formatted input is convenient, but it stops when it reaches a character that does not belong to the requested value.
It is worth comparing the direction in which input and output data move. The insertion operator, <<, sends data to std::cout for display. The extraction operator, >>, takes data from std::cin and stores it in a variable. Mixing up these operators is a common mistake that usually causes a compilation error.
If conversion to the requested data type fails, the stream enters a failure state. Further formatted input operations are skipped until that state is cleared. Repeating the same extraction without handling the failure does not automatically remove the invalid characters.
For this reason, the result of an input operation should be checked before the destination variable is used:
int age;
if (std::cin >> age)
{
std::cout << "You are " << age << " years old.\n";
}
else
{
std::cout << "That was not a valid age.\n";
}
The previous contents of the destination variable should not be treated as proof that a new extraction succeeded.
A program may also read several inputs in one statement by chaining extraction operations. This is convenient when several related values need to be collected:
#include <iostream>
int main()
{
int width;
int height;
std::cout << "Enter the width and height separated by a space: ";
std::cin >> width >> height;
std::cout << "The area is " << width * height << ".\n";
return 0;
}
When reading several values, std::cin automatically skips leading whitespace characters, including spaces, tabs, and newlines. For instance, a user may enter 15, type a space, and then enter 10. The whitespace separates the values, allowing 15 to be stored in width and 10 in height.
When the user enters characters that cannot be converted to the expected type, such as letters when an integer is required, the conversion fails and std::cin enters an error state. Further formatted input operations are then ignored until the failure state is cleared and the unwanted input is handled.
Exercise: Reading Input with std::cinStarter code, hints and solutionOpenClose
Practice: Reading Input with std::cin
Work through the mission, reveal hints only when needed, and compare your result with the model solution.
Your challenge
Run the program with the additional input 3 4. Add a labeled output line showing width and height, then explain the area result.
Mission checklist
- Run the starter as a baseline, then predict the change requested in Your challenge.
- Make that change in your editor; use the lesson-specific hints if you need help.
- Compile and run your answer, then compare with the worked solution and explain the result.
Starter program
This is the working baseline, not the completed answer. Compile as C++20, then make the change described above.
#include <iostream>
int main()
{
int width{};
int height{};
std::cout << "Enter the width and height separated by a space: ";
if (!(std::cin >> width >> height))
{
std::cout << "Invalid dimensions\n";
return 1;
}
std::cout << "The area is " << width * height << ".\n";
return 0;
}Hints
In std::cin >> width >> height, the first integer goes into width and the second into height. A space or newline can separate the two numbers.
Try a small valid pair such as 3 and 4. Multiply the two stored integers to predict the area; the prompt itself is printed before either value is read.
Worked solution
For the additional input 3 4, width receives 3 and height receives 4. The added diagnostic line shows that mapping; their product is 12.
#include <iostream>
int main()
{
int width{};
int height{};
std::cout << "Enter the width and height separated by a space: ";
if (!(std::cin >> width >> height))
{
std::cout << "Invalid dimensions\n";
return 1;
}
std::cout << "The area is " << width * height << ".\n";
std::cout << "width = " << width << ", height = " << height << '\n';
return 0;
}
Example input
3 4
Example output
Program output only; your terminal may also echo the input you type.
Enter the width and height separated by a space: The area is 12.
width = 3, height = 4
0 comments
No comments yet. Be the first.