These are the notes for C++ episode 4. Until now every value lived inside the code. Here the user types it in. You will learn why programs need input, how cin >> reads numbers (one or several at a time), why cin >> name keeps only the first word and how getline fixes it, the famous empty-name bug after cin >> seat and its fix getline(cin >> ws, name), what happens when someone types abc for a number (cin.fail()), and then type casting: implicit vs explicit conversion, static_cast<double>, why the position of the cast matters, static_cast<char>, static_cast<int> vs round(), and the old C-style cast. Every example below was compiled with g++ -O2 -std=c++17 main.cpp -o main (g++ 13.3, the same command as the SyntaxPilot compiler) and run with the input shown, using printf '<input>' | ./main.
Piped input is not echoed. When input comes from a pipe (or the SyntaxPilot input box), the numbers you "typed" do not appear in the output. That is why you see
Enter the bill: Each of 4 pays: 120on one line. In a real terminal you would type480after the prompt and press Enter, so it would look likeEnter the bill: 480and the answer on the next line.
The problem: the hostel's bill splitter
Remember Aman's bill splitter from episode 3? Now the whole hostel wants it, and everyone has a different bill: ₹480, ₹1,250, ₹96. But the bill is written inside the code:
#include <iostream>
#include <string>
using namespace std;
int main() {
int bill = 250;
cout << "Each of 4 pays: " << bill / 4.0 << endl;
return 0;
}
Output: Each of 4 pays: 62.5. A friend's bill is ₹480, so Aman edits line 6 to int bill = 480; and runs again. Output: Each of 4 pays: 120.
It works, but nobody else can use it: his friends can't code. A value baked into the source code like this is called hard-coded. The program needs to ask for the bill while it runs.
The fix: cin, the ear of the program
Think of a waiter: cout (character output) is his mouth, cin (character input) is his ear.
| At a restaurant | In C++ | Direction |
|---|---|---|
| The waiter speaks: "Your bill is ₹250" | cout << "..." |
arrows point towards cout: data goes out to the screen |
| The waiter listens: "Two dosas, please" | cin >> bill |
arrows point away from cin, into the variable |
| He writes it on his pad | cin >> bill; |
the value is stored in bill |
#include <iostream>
#include <string>
using namespace std;
int main() {
int bill;
cout << "Enter the bill: ";
cin >> bill;
cout << "Each of 4 pays: " << bill / 4.0 << endl;
return 0;
}
| Input | Output |
|---|---|
480 |
Enter the bill: Each of 4 pays: 120 |
1250 |
Enter the bill: Each of 4 pays: 312.5 |
One program, any bill, and nobody touched the code. int bill; has no value at first; cin >> bill; fills it.
cinis a stream: a flow of characters coming from the keyboard, one after another, like water through a pipe.>>is the extraction operator: it extracts (takes out) a value from the stream and puts it into the variable.coutuses<<, the insertion operator.- In a real terminal the program stops at
cinand waits for you. On SyntaxPilot you type the input in the box at the bottom before you press Run.
Short snippets. From here on, when only the inside of
mainis shown, put those lines into the same skeleton as above (#include <iostream>,#include <string>,using namespace std;,int main() {...return 0; }). That is exactly what the video runs.
Reading two values at once
The number of friends changes too. Chain the arrows:
int bill, friends;
cin >> bill >> friends;
cout << bill << " split " << friends << " ways" << endl;
| Input | Output |
|---|---|
480 5 (one line, a space between) |
480 split 5 ways |
480, Enter, 5 (two lines) |
480 split 5 ways |
Same result. cin >> skips any spaces, tabs and Enters before a value, then reads values in order. Spaces, tabs and newlines together are called whitespace.
Full names: cin stops at a space, getline reads the line
Aman's cousin runs a small hotel and wants the guest register on a computer. Ravi Kumar checks in:
string name;
cout << "Your name: ";
cin >> name;
cout << "Hello, " << name << "!" << endl;
Input Ravi Kumar. Output: Your name: Hello, Ravi!
The surname is gone, with no error. Why? cin >> treats whitespace as the end of a value. It reads Ravi, stops at the space, and Kumar is left waiting, unread. (A string is C++'s box for text; it needs #include <string>.)
The fix is getline, a function: a named piece of ready-made code you call by its name with round brackets. getline(cin, name) reads the whole line, spaces and all, up to the Enter (the Enter itself is thrown away, not stored). Change one line:
getline(cin, name);
Input Ravi Kumar. Output: Your name: Hello, Ravi Kumar!
Rule: text that can contain spaces? Use getline.
The empty-name bug: getline after cin >>
The register now asks for the seat (room) number first with cin >>, then the name with getline. The name is printed between square brackets so we can see exactly what is inside:
int seat;
string name;
cin >> seat;
getline(cin, name);
cout << "Seat " << seat << ": [" << name << "]" << endl;
Input 42, Enter, Ravi Kumar (that is printf '42\nRavi Kumar'). Output: Seat 42: []
The name is empty. In a real terminal the program would not even wait for you to type it.
Why: the leftover Enter on the counter
Typed characters wait in the input buffer, a waiting area in memory, until something reads them. After typing 42 and Enter, the buffer holds 42\n.
| At the counter | In C++ |
|---|---|
| Clerk 1 takes only the number 42 and leaves the Enter on the counter | cin >> seat; reads 42; the \n stays in the buffer |
| Clerk 2 reads up to the first Enter, finds it at once: an empty line | getline(cin, name); reads "" and stops |
| Wipe the counter first, then read the name | getline(cin >> ws, name); |
The fix: cin >> ws
ws (short for whitespace) is a helper that skips all leftover whitespace. Put it right inside getline:
getline(cin >> ws, name);
Same input, output: Seat 42: [Ravi Kumar]
You will also see cin.ignore() used for the same job. It throws away (ignores) the next character in the buffer, which is the leftover \n:
cin >> seat;
cin.ignore();
getline(cin, name);
With input 42\nRavi Kumar this also prints Seat 42: [Ravi Kumar]. The safer cin.ignore(numeric_limits<streamsize>::max(), '\n'); (needs <limits>) throws away the rest of the line, even extra spaces after 42 (also verified).
Rule: after cin >>, before getline, clear the leftover Enter.
When the user types "abc" for a number: cin.fail()
Users don't always type what you expect. A friend types abc for the bill:
int bill;
cin >> bill;
cout << "Bill: " << bill << endl;
cout << "cin failed? " << cin.fail() << endl;
Input abc. Output:
Bill: 0
cin failed? 1
An int box can't hold letters. Since C++11, cin stores 0 in the variable, sets its fail flag, and stops reading: every later cin >> does nothing until the error is cleared (that needs cin.clear(), covered later). cin.fail() returns 1 (true) when the last read failed, 0 otherwise. No crash, just a silently wrong bill. Two more cases (verified):
| Code | Input | Result |
|---|---|---|
int bill; cin >> bill; |
12abc |
bill = 12, cin.fail() = 0 (it reads digits and stops at a) |
int bill; cin >> bill; |
62.5 |
bill = 62, cin.fail() = 0 (stops at the .) |
int bill = 7, friends = 9; cin >> bill >> friends; |
abc 5 |
prints 0 9 1: bill became 0, friends was never read |
In the next episode, with if and else, you will check this flag and ask the user to try again.
Type casting: static_cast
Back to the splitter, with both values typed in:
int bill, friends;
cin >> bill >> friends;
cout << "Each pays: " << bill / friends << endl;
Input 250 4. Output: Each pays: 62
Integer division is back (int ÷ int = int, the .5 is chopped). Last episode we wrote 4.0, but friends is a variable now. The obvious try, bill / friends.0:
main.cpp:8:44: error: expected ';' before numeric constant
The .0 trick only works on a written number (a literal), not on a variable name. We need to say: treat this int as a double, just for this calculation. That is type casting, converting a value from one type to another on purpose:
cout << "Each pays: " << static_cast<double>(bill) / friends << endl;
Input 250 4. Output: Each pays: 62.5
static_cast<double>(bill) means "give me bill's value as a double". One side became a double, so the whole division happens in doubles, exactly like 250 / 4.0. The variable bill itself is not changed: it is still an int holding 250.
Cast before you divide: the milk jug
Pour the milk into a measuring jug first, then share: everyone gets exactly 62.5 ml. Share it in egg trays (whole units only) and pour into the jug afterwards: the half is already lost.
cout << "Each pays: " << static_cast<double>(bill / friends) << endl;
Input 250 4. Output: Each pays: 62
bill / friends ran first, in ints, giving 62. Only then was 62 turned into the double 62.0, which cout prints as 62. Cast the operand, not the answer.
Implicit vs explicit conversion
| Kind | Who does it | Examples (verified output) |
|---|---|---|
| Implicit | C++, automatically | 5 + 2.5 prints 7.5 (5 becomes 5.0); double d = 62; prints 62 (stored as 62.0); int n = 4.9; prints 4 (chopped!); char c = 66; prints B |
| Explicit (casting) | You ask for it | static_cast<double>(bill) |
| C-style cast (old) | You ask for it | (double)bill / friends and double(bill) / friends both print 62.5 for 250 and 4 |
The C-style cast works, but it is easy to miss when reading code, it is hard to search for, and it will force almost any conversion, even dangerous ones. Prefer static_cast: it stands out, it's easy to search for, and the compiler refuses conversions that make no sense.
char and int casts
Cinema seats go A, B, C. Seat A is taken, so give the next one:
char seat = 'A';
cout << seat + 1 << endl;
cout << static_cast<char>(seat + 1) << endl;
Output (no input):
66
B
As in episode 2, a char is secretly a small number: 'A' is 65. seat + 1 is an int (66), so cout prints a number. static_cast<char> shows the same value as a letter.
The other way: a 4.7-star rating. round lives in the header <cmath> (a header is a file of ready-made code you bring in with #include):
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double rating = 4.7;
cout << static_cast<int>(rating) << endl;
cout << round(rating) << endl;
cout << round(4.2) << endl;
return 0;
}
Output (no input):
4
5
4
static_cast<int> chops the decimal part (towards zero, like integer division). round() gives the nearest whole number (4.5 rounds up to 5). Note round returns a double; wrap it as static_cast<int>(round(x)) if you need an int. Chop or round: pick the one you mean.
Common mistakes (and the real g++ messages)
| Mistake | Code | What g++ says / what happens | Fix |
|---|---|---|---|
Arrows the wrong way on cin |
cin << bill; |
error: no match for 'operator<<' (operand types are 'std::istream' {aka 'std::basic_istream<char>'} and 'int') followed by a wall of notes |
cin >> bill; |
cin >> for a full name |
cin >> name; with Ravi Kumar |
no error; name is "Ravi" |
getline(cin, name); |
getline right after cin >> |
cin >> seat; getline(cin, name); |
no error; name is empty |
getline(cin >> ws, name); or cin.ignore(); first |
.0 on a variable |
bill / friends.0 |
error: expected ';' before numeric constant |
static_cast<double>(bill) / friends |
| No round brackets in the cast | static_cast<double> bill / 4 |
error: expected '(' before 'bill' |
static_cast<double>(bill) / 4 |
| Cast too late | static_cast<double>(bill / friends) |
no error; still 62 |
cast an operand, before dividing |
getline into a number |
int n; getline(cin, n); |
error: no matching function for call to 'getline(std::istream&, int&)' |
getline is for string; use cin >> n |
| Trusting input blindly | cin >> bill; with abc |
no error; bill is 0, cin.fail() is 1 |
check cin.fail() (with if, next episode) |
For cin << bill, read only the first line: istream is the type of cin (an input stream), which has no <<. Flipped to cin >> bill; cout << bill << endl;, input 250 prints 250.
Mini project: report card
Read a roll number, a full name and three marks; print the total, the exact average, the rounded average, and whether the student passed (every mark at least 33).
#include <iostream>
#include <string>
using namespace std;
int main() {
int roll, m1, m2, m3;
string name;
cin >> roll;
getline(cin >> ws, name);
cin >> m1 >> m2 >> m3;
int total = m1 + m2 + m3;
double avg = static_cast<double>(total) / 3;
cout << "Roll " << roll << ": " << name << endl;
cout << "Total: " << total << " / 300" << endl;
cout << "Average: " << avg << endl;
cout << "Rounded: " << static_cast<int>(avg + 0.5) << endl;
cout << boolalpha << "Passed: " << (m1 >= 33 && m2 >= 33 && m3 >= 33) << endl;
return 0;
}
Input (printf '17\nPriya Sharma\n78 91 85'):
17
Priya Sharma
78 91 85
Output:
Roll 17: Priya Sharma
Total: 254 / 300
Average: 84.6667
Rounded: 85
Passed: true
getline(cin >> ws, name)skips the Enter left after the roll number, so the full name survives.static_cast<double>(total) / 3keeps the decimals;coutshows 6 significant digits, hence84.6667.static_cast<int>(avg + 0.5)is the classic rounding trick for positive numbers: 84.67 + 0.5 = 85.17, chopped to 85.boolalphamakescoutprinttrue/falseinstead of1/0.
Practice
- Read a temperature in Celsius and print it in Fahrenheit (F = C × 9 / 5 + 32).
- Read your full name and print how many characters it has.
- Read two ints and print their exact average.
- Read a letter and print the next three letters.
Solution
1. Use double, so 37.5 also works. Input 37 prints 37 C = 98.6 F.
#include <iostream>
using namespace std;
int main() {
double celsius;
cin >> celsius;
double fahrenheit = celsius * 9 / 5 + 32;
cout << celsius << " C = " << fahrenheit << " F" << endl;
return 0;
}
2. getline keeps the space; name.length() counts characters (the space counts). Input Ravi Kumar prints Ravi Kumar has 10 characters.
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
getline(cin, name);
cout << name << " has " << name.length() << " characters" << endl;
return 0;
}
3. Cast before dividing. Input 7 4 prints Average: 5.5 (without the cast: 5).
#include <iostream>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
cout << "Average: " << static_cast<double>(a + b) / 2 << endl;
return 0;
}
4. Cast each sum back to char. Input C prints D E F.
#include <iostream>
using namespace std;
int main() {
char letter;
cin >> letter;
cout << static_cast<char>(letter + 1) << " "
<< static_cast<char>(letter + 2) << " "
<< static_cast<char>(letter + 3) << endl;
return 0;
}
Quick quiz
What does this print?
int a = 7, b = 2;
cout << static_cast<double>(a / b) << endl;
- A.
3.5 - B.
3 - C.
4 - D. Compile error
Answer
B: 3. a / b runs first, as int ÷ int, giving 3. Casting 3 to a double gives 3.0, which cout prints as 3. Cast an operand instead: static_cast<double>(a) / b prints 3.5 (both verified).
Interview questions
- What is the difference between
cin >>andgetline?cin >>skips leading whitespace and reads one "word" or number, stopping at the next whitespace.getline(cin, s)reads everything up to the newline, spaces included, and discards the newline. - Why does
getlinereturn an empty string aftercin >> x?cin >>leaves the Enter (\n) in the input buffer;getlinesees it first and stops. Fix withcin >> wsorcin.ignore(). - What happens if the user enters letters into an
int? Extraction fails: the variable gets 0 (since C++11), the stream's fail flag is set (cin.fail()returns true), and later reads do nothing untilcin.clear()is called and the bad input is ignored. - What is the difference between implicit and explicit conversion? Implicit conversion is done by the compiler automatically (e.g.
inttodoublein5 + 2.5); explicit conversion (a cast) is written by the programmer, e.g.static_cast<double>(x). - Why prefer
static_castover a C-style cast? It is visible and searchable, it states intent, and it rejects unrelated conversions that a C-style cast would silently allow. - What is the difference between
static_cast<double>(a) / bandstatic_cast<double>(a / b)? The first converts before dividing (floating-point division, 3.5 for 7 and 2); the second divides integers first (3) and then converts (3.0). - Does
static_cast<int>(4.7)round? No, it truncates towards zero: 4 (and -4 for -4.7). Useround()from<cmath>to round to the nearest (5, and -5 for -4.7).
Glossary
| Term | Plain meaning | Example |
|---|---|---|
| Input | Data that comes into a program while it runs, usually typed by the user | typing 480 for the bill |
| Output | Data the program sends out, usually to the screen | Each pays: 62.5 |
| Hard-coded | A value written directly in the source code, so changing it means editing the code | int bill = 250; |
| Variable | A named box in memory that holds a value | int bill; |
cin |
Character input: the standard input stream, connected to the keyboard | cin >> bill; |
cout |
Character output: the standard output stream, connected to the screen | cout << bill; |
| Stream | A flow of characters, one after another, into or out of a program | keyboard → cin → your variables |
istream |
The type of input streams such as cin (it appears in error messages) |
'std::istream' |
Extraction operator >> |
Takes a value out of an input stream and stores it in a variable | cin >> bill >> friends; |
Insertion operator << |
Puts a value into an output stream | cout << "Hi"; |
| Whitespace | Spaces, tabs and newlines (Enters) | the space in 480 5 |
Newline \n |
The invisible character produced by pressing Enter | 42\nRavi Kumar |
string |
C++'s type for text; needs #include <string> |
string name = "Ravi"; |
| Function | A named piece of ready-made code you call with round brackets | getline(cin, name), round(4.7) |
getline |
Function that reads a whole line, spaces included, into a string |
getline(cin, name); |
| Buffer (input buffer) | A waiting area in memory where typed characters sit until something reads them | \n left behind after cin >> seat |
ws |
Helper that skips all leading whitespace in an input stream | getline(cin >> ws, name); |
cin.ignore() |
Throws away the next character (or up to a given character) from the buffer | cin.ignore(); before getline |
cin.fail() |
Returns 1 (true) if the last read failed, e.g. letters for an int |
prints 1 for input abc |
| Fail flag | The stream's internal "something went wrong" marker; while set, reads do nothing | set by abc into an int |
| Integer division | int ÷ int, which chops the decimal part | 250 / 4 is 62 |
| Literal | A value written directly in code | 4.0, 'A', "Hello" |
| Operand | A value an operator works on | in bill / friends, both are operands |
| Type casting | Converting a value from one type to another on purpose | static_cast<double>(bill) |
| Implicit conversion | A conversion C++ does automatically | 5 + 2.5 → 7.5; int n = 4.9; → 4 |
| Explicit conversion | A conversion you write yourself (a cast) | static_cast<char>(66) → B |
static_cast<T>(x) |
The modern C++ cast: gives x's value as type T; x itself is unchanged |
static_cast<int>(4.7) → 4 |
| C-style cast | The old cast syntax from C: the type in round brackets | (double)bill |
| Truncate (chop) | Drop the decimal part without rounding | static_cast<int>(4.7) → 4 |
round() |
Function from <cmath> that gives the nearest whole number (as a double) |
round(4.7) → 5 |
| Header | A file of ready-made code brought in with #include |
#include <cmath> |
<cmath> |
The header with maths functions: round, sqrt, pow ... |
#include <cmath> |
char |
One character, stored as a small number (its character code) | 'A' is 65 |
boolalpha |
Makes cout print true/false instead of 1/0 |
cout << boolalpha << true; |
| Compile error | A mistake g++ finds before the program runs; no program is produced | expected '(' before 'bill' |
Summary
- Hard-coded values force you to edit code;
cin >> xreads input into a variable while the program runs. cin >> a >> breads several values in order, skipping whitespace between them.cin >>stops at a space; usegetline(cin, s)for text with spaces.- After
cin >>, the Enter stays in the buffer: usegetline(cin >> ws, s)(orcin.ignore()first). - Letters typed for a number: the variable becomes 0 and
cin.fail()is 1. Never trust input blindly. - Implicit conversion happens by itself; explicit conversion (casting) is written by you. Prefer
static_castover the C-style(double)x. static_cast<double>(a) / b: cast before dividing, or the decimals are already lost.static_cast<char>turns a code back into a letter;static_cast<int>chops;round()from<cmath>rounds.
Next episode: if / else and switch. So far every program runs every line, no matter what. What if the user types abc? What if the bill is over ₹200 and earns free chai? Next time your program learns to make decisions.