Input and output with iostream
A program becomes useful when it can receive a value, work with it, and report a result. C++ stream objects provide a beginner-friendly way to communicate through standard input and standard output.
Learning objectives
- Use
std::coutto write a prompt and result. - Use
std::cin >>to read one formatted integer. - Trace how input becomes a variable value and then part of an output expression.
- Recognize why real programs must validate input.
Prerequisites: write and run a basic C++ program, declare variables, and understand expressions. Review Your first C++ program and Variables, values, and data types first.
Why input and output exist
A calculation hidden inside a program is not very helpful. Input gives a program facts that can vary: an age, a quantity, a menu choice, or a measurement. Output gives the user a result they can use. In this lesson, a terminal window is the visible input/output destination, but standard streams can also be connected to files or test tools.
person types characters → standard input → program variable program evaluates expression → standard output → visible result
Stream analogy
A stream is like a channel through which characters move. std::cin is the standard input stream; std::cout is the standard output stream. The analogy helps with direction, not with physical plumbing: streams are C++ library objects that manage character input and output through an associated buffer.
Read one whole-number value
#include <iostream>
int main() {
int age{};
std::cout << "Enter your age: ";
std::cin >> age;
std::cout << "Next year, you will be "
<< age + 1 << ".\n";
}Learning simplification: this first example assumes the user enters a valid integer. If extraction fails, age remains at its initialized value of zero, so the later calculation would be misleading. A later input-validation lesson shows how to check the stream before using the value.
Code, line by line
#include <iostream>makes declarations for the standard stream objects available.int age{};creates an integer variable and initializes it to zero. The braces make the initialization explicit.- The first output statement writes a prompt. There is no newline yet because the answer should appear after the prompt in a typical terminal.
std::cin >> age;performs formatted extraction: it reads characters from standard input, interprets a suitable whole-number representation, and stores the resulting integer inagewhen extraction succeeds.- The next output statement writes an explanatory label.
age + 1reads the entered value and calculates the following year’s age.- The final output inserts the result, a period, and a newline.
Expected interaction
Enter your age: 19 Next year, you will be 20.
The 19 line is input typed by the user. The program’s calculated output is the second line. A terminal may show the prompt and typed input on the same visual line; that is normal for this example.
Execution trace
ageis initialized to 0.- The prompt is written to standard output.
- The program waits for formatted input. If the user types
19and confirms the input, extraction converts those characters to integer value 19 and stores it inage. - The expression
age + 1becomes19 + 1, then 20. - The output stream receives the label, 20, punctuation, and a newline.
age = 0 prompt written user supplies "19" formatted extraction succeeds → age = 19 age + 1 → 20 result written
What happens internally
std::cin is a standard input stream object associated with the environment’s standard input. The extraction operator for an integer skips leading whitespace, reads characters that form an integer according to the stream’s formatting rules, converts them, and stores the result if it can. std::cout receives output values through insertion operations and writes their character representation to standard output. The exact terminal, buffer, and device behavior depend on the platform; the source-level contract is the stream operation.
When input is not valid
If a user types hello where an integer is required, integer extraction cannot produce the intended int value. The stream records a failure state; it does not magically choose a sensible age. This lesson does not yet use conditions to recover from that state, but you should already understand the design rule: never assume external input is valid. A later control-flow lesson will test stream state and ask again or show a clear error.
Common beginner mistakes
- Using
<<for input: output inserts intostd::cout; input extracts fromstd::cinwith>>. - Forgetting to initialize a variable: start with a deliberate value even if input is expected to replace it.
- Assuming the entered text is always valid: formatted extraction can fail. Validate before making important decisions from input.
- Expecting
std::cin >> nameto read a full sentence: formatted string extraction stops at whitespace. A later string lesson introducesstd::getlinefor complete lines. - Confusing a prompt with input:
std::coutasks the question;std::cinreceives the answer. - Omitting a space in the prompt: a trailing space after the colon makes terminal interaction easier to read.
Practical exercises
- Modify the program to read the number of pages you read today and print how many pages you will have read after 10 more.
- Change
agetotemperature_celsiuswith typedouble. Read a temperature and print it back with a label. - Enter a non-number for the original program. Observe that it cannot calculate the next age. In your own words, explain why validation is necessary.
- Write prompts and output labels for a program that asks for the number of tickets and price of one ticket. Do not calculate the total until you can state the intended input types.
- Predict the result when the user enters 0, then compile and test it.
Assessment: check your understanding
1. Which stream receives the user’s typed input in this lesson?
Answer: std::cin. Why: It is the standard character input stream used with the extraction operator >>.
2. What does std::cin >> age; try to do?
Answer: Read a formatted integer from standard input and store it in age. Why: The destination variable’s type guides the intended conversion.
3. If the user enters 19, what does age + 1 produce?
Answer: 20. Why: The input operation stores 19 in age, then the addition evaluates that value plus one.
4. Why is a prompt often printed without a newline?
Answer: So a terminal user can type the answer after the prompt on the same line. Why: The prompt describes the input expected next.
5. Does formatted integer input guarantee that a user typed a valid integer?
Answer: No. Why: Extraction can fail, so later programs need to check input state and handle invalid values.
Revision summary
std::cout writes to standard output and std::cin reads from standard input. Formatted extraction can place a valid typed integer into a variable; then ordinary expressions can use it. Input comes from outside the program, so thoughtful programs validate it rather than trusting it blindly.