Jan 23, 2026
## Chapter 3: Input and Output
(Input and Output in C++)
So far we have:
- written programs
- created variables
Now the question arises:
How to get information from the user?
And how to display it on the screen?
This is where a C++ program becomes interactive.
### Taking input from the user:
When we need to get data from the keyboard,
we use `cin`.
**Basic Input/Output Example**
C++
```
#include <iostream>
#include <string>
using namespace std;
int main() {
string userName;
int userAge;
cout << "What is your name? ";
cin >> userName; // input from the keyboard
cout << "How old are you? ";
cin >> userAge;
cout << "Hello, " << userName
<< "! You are " << userAge
<< " years old." << endl;
return 0;
}
```
Now let's understand it line by line:
**cout – For displaying output**
C++
```
cout << "What is your name? ";
```
- cout → displays text on the screen
- << → sends data towards the output
Meaning:
Display the question on the screen
**cin – For taking input**
C++
```
cin >> userName;
```
- cin → takes data from the keyboard
- > > → extraction operator
- It does the opposite of <<
The value that the user types,
goes into the variable.
**Taking multiple inputs**
C++
```
cin >> userAge;
```
- cin works perfectly for numbers
- No problem for int, float, double
**Combining and displaying output**
C++
```
cout << "Hello, " << userName <<
"! ...";
```
- With <<, you can print multiple things together
- Text + variables combine easily
**Important Limitation of cin**
C++
```
cin >> userName;
``` This:
Stops input when a space is encountered.
Example:
```cpp
Input: Rahul Kumar
Stored value: Rahul
```
The full name is not captured.
### Understanding Input/Output:
`cin` (console input) takes data from the keyboard.
`>>` is the extraction operator (the reverse of
`<<`).
For strings with spaces, use `getline(cin, variableName)`.
**`getline()` for Strings with Spaces**
When:
- Full name
- Complete sentence
- Address
is required as input,
we should use `getline()`.
**Example: Using `getline()`**
C++
```
#include <iostream>
#include <string>
using namespace std;
int main() {
string fullName;
cout << "Enter your full name: ";
getline(cin, fullName); // Reads the entire line, including
spaces
cout << "Hello, " << fullName <<
endl;
return 0;
}
```
How does `getline()` work?
- Reads the entire line
- Accepts spaces
- Ends input when Enter is pressed
Therefore, it is best for real-world input.
**`cin` vs `getline()` (Quick Comparison)**
| Feature |
`cin` | `getline()` |
| -------------- | ------ | ----------- |
| Reads spaces |
No | Yes |
| Simple input |
Yes | Yes |
| Full sentence |
No | Yes |
Easy way to remember in one line:
- `cout` → for displaying
- `cin` → for taking input
- `>>` → extracts input
- `<<` → sends output
- `getline()` → reads the entire line