
Let’s think it through · Start with a story
The robot does not know how many candies you have, so it has to ask. You enter 3, and it tells you how many you will have after adding two more.
Break down the process
- InputType 3
- Storecandies becomes 3
- CalculateAdd 2 to 3
- OutputDisplay 5
std::cin is commonly used to read input, and std::cout is commonly used to produce output.
Input brings outside data into a program; output sends results back out. Variables connect the two directions by remembering the numbers just received.
01Why do programs need input and output?
Many programs need to receive data, process it, and tell us the result.
02How does cout produce output?
std::cout << "Score: " << 95 << '\n';std::cout is the standard output stream object. The << operator writes the values on its right into the output stream in sequence.
03How does cin read input?
int age;
std::cin >> age;std::cin is the standard input stream object. The >> operator tries to read and convert the input according to the variable’s type.
04A complete small example
#include <iostream>
int main() {
int a, b;
std::cin >> a >> b;
std::cout << a + b << '\n';
return 0;
}Given the input 3 5, the program outputs 8.
05How does input data become a variable?
Terminal input is essentially a sequence of characters. std::cin tries to convert it according to the target variable’s type. If you enter hello for an integer variable, the input operation fails.
06How do spaces and newlines affect cin?
When the ordinary >> operator reads a number or word, it usually skips leading whitespace. Spaces, tabs, and newlines commonly act as separators. To read an entire line of text, use std::getline.
07Is the program really talking with us?
“Talking with your program” is just an analogy. More precisely, cin and cout are input and output data streams.
What you have learned
- cin and cout are part of C++ standard input and output streams.
- cout writes to standard output, and cin reads from standard input.
- Input characters are converted according to the variable type.
- The ordinary >> operator commonly reads whitespace-separated data.
- You can use getline to read a whole line of text.
Your turn
A program asks for two integers, but you enter only one and stop. Why might it not produce a result?
Have an answer? Click to see the explanation
It may still be waiting for the second input. Check the expected format and number of values before assuming the program is broken.