Reading a Problem's Input
GOALRead a problem's Input format paragraph and write exactly the code that matches it.
Every problem describes how it hands you its data in an Input format paragraph: how many lines there are, and how many values sit on each line. Those two counts decide the code you write. By the end of this lesson you will be able to look at any format and write the code straight away.
ON THIS PAGE
- The example
- Line by line
- Watch it run
- What reading the input actually does
- Two numbers on one line — the crash everyone hits
- Cutting the line into pieces
- Turning the pieces into numbers
- Every shape you will meet
- When the line is text with spaces in it
- Learning to read the error message
- A count, then that many values (a look ahead)
- Turning a format into code in four steps
- Common mistakes
- Key words
- Quick check
- Now you try
//THE EXAMPLE
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int a, b;
cin >> a >> b;
cout << n << endl;
cout << a + b << endl;
return 0;
}(input: 5\n3 4) 5 7
//LINE BY LINE
Watch it run
The format: line 1 holds n, line 2 holds a and b. This is the text the judge sends.
What reading the input actually does
cin >> x reads ONE whitespace-separated piece from the input and puts it in x. A space and a new line are the same separator to cin, so where a line ends makes no difference to it.
See with your own eyes what you read:
int a, b;
cin >> a >> b;
cout << "a=" << a << " b=" << b << endl;(input: 3 4) a=3 b=4
That program prints exactly a=3 b=4 whether the input arrives as one line 3 4 or as two lines, 3 then 4. That is why the shape of the input rarely troubles you in C++.
Two numbers on one line — the crash everyone hits
C++ does not have this problem. cin >> treats a space, a tab and a new line all the same way — as a separator to skip over. So one line saying 3 4 and two lines saying 3 and 4 look identical to cin >> a >> b;.
Two numbers on one line — the version that works:
int a, b;
cin >> a >> b; // one line "3 4", or two lines — both work
cout << a + b << endl;(input: 3 4) 7
The COUNT still matters in C++ though. If the format promises two values and you write cin >> a >> b >> c;, the third value never arrives: cin fails, c keeps whatever junk was in it, and what you print is a meaningless number.
Careful the other way: when the input really is two lines with one number each, writing int(input()) twice is CORRECT. It is only wrong when both numbers sit on one line. Do not over-correct and start cutting up lines that hold a single number.
Cutting the line into pieces
In C++ you never cut the line yourself — cin sees the input as a stream of whitespace-separated pieces, and each >> pulls one piece off. It is still worth knowing what those pieces are.
Three pieces:
int a, b, c;
cin >> a >> b >> c;
cout << a << "|" << b << "|" << c << endl;(input: 7 2 9) 7|2|9
Cut up, but still not numbers:
string a, b;
cin >> a >> b;
cout << a + b << endl;(input: 3 4) 34
Turning the pieces into numbers
In C++ the conversion is decided by the variable's type. Declare int a; and cin >> a turns the piece it read into a number for you. Declare string a; and it keeps it as text.
Two numbers on one line — the commonest shape of all:
int a, b;
cin >> a >> b;
cout << a + b << endl;(input: 3 4) 7
Every shape you will meet
Everything an Input format paragraph can say is really one of a handful of shapes. Learn them once and after that you only have to recognise them.
| What the problem says | C++ code |
|---|---|
Нэг бүхэл тоо n / A single integer n | int n; cin >> n; |
Нэг мөрөнд хоёр бүхэл тоо a b / Two integers a b on one line | int a, b; cin >> a >> b; |
Нэг мөрөнд гурван тоо a b c / Three integers a b c on one line | int a, b, c; cin >> a >> b >> c; |
Нэг мөрөнд n тоо / A line of n integers | Давталт хэрэгтэй / needs a loop — cin >> x; |
| Нэг бутархай тоо / A single decimal | double x; cin >> x; |
| Зайгүй нэг үг / A single word, no spaces | string w; cin >> w; |
| Зайтай бүтэн мөр текст / A whole line of text with spaces | string s; getline(cin, s); |
A number sitting alone on its line:
int n;
cin >> n;
cout << n * 2 << endl;(input: 12) 24
Three numbers on one line:
int a, b, c;
cin >> a >> b >> c;
cout << a + b + c << endl;(input: 7 2 9) 18
A decimal value:
double x;
cin >> x;
cout << x * 2 << endl;(input: 1.5) 3
Never print a prompt like "Enter a number:". The judge compares your output character by character, so any extra text turns a correct answer into a wrong one.
When the line is text with spaces in it
cin >> name stops at the first space, so from "Bat Erdene" you only get "Bat". When you need the whole line, right to its end, use getline(cin, name).
Right:
string name;
getline(cin, name);
cout << "Hello, " << name << endl;(input: Bat Erdene) Hello, Bat Erdene
Wrong:
string name;
cin >> name;
cout << "Hello, " << name << endl;(input: Bat Erdene) Hello, Bat
Writing getline(cin, s) straight after cin >> n leaves s EMPTY: the Enter that followed the number is still sitting in the input, and getline reads that leftover instead. The getline lesson deals with this properly.
Learning to read the error message
In C++ cin throws nothing — it fails quietly. If you read with >> after the input has run out, the variable is left with no value and EVERY later read stops working. The program does not crash, so the judge says "Wrong Answer" rather than "Runtime Error", which makes the cause harder to find.
Reading more values than the format has:
int a, b, c;
cin >> a >> b >> c; // ✗ оролтод ердөө хоёр тоо байхад гурав уншив
cout << a + b + c << endl;The number of >> reads must match the number of values in the input format exactly. If you are unsure, print what you read and look at it.
A count, then that many values (a look ahead)
This section uses loops and lists, which come later. You do not have to learn them now. You will want to copy from here while solving problems, though, so here they are.
Line 1 holds HOW MANY numbers there are, then come the numbers themselves. Read n, then run a loop n times, reading one number each time round.
Line 1: 3. Line 2: 1 2 3. Print the sum.
int n;
cin >> n;
int total = 0;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
total += x;
}
cout << total << endl;(input: 3\n1 2 3) 6
That loop works for both layouts: it prints 6 whether 1 2 3 arrives on one line or on three separate lines. This is what cin ignoring line breaks buys you.
One number per line:
int n;
cin >> n;
int total = 0;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
total += x; // ЯГ ижил код — cin мөрийг үл хайхарна
}
cout << total << endl;(input: 3\n1\n2\n3) 6
n lines, two numbers on each:
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int a, b;
cin >> a >> b;
cout << a + b << endl;
}(input: 2\n1 2\n10 20) 3 30
Turning a format into code in four steps
On every new problem, do the same four things to the Input format paragraph. After a few problems it becomes automatic.
- 1.Count how many LINES the input has.
- 2.Count how many VALUES sit on each line.
- 3.Write the matching line of code for each line of input.
- 4.Add no prompt and no extra text to your output.
In C++ step 3 is even simpler: one >> per value, in the order the format lists them. You need not count where the lines end — only the values.
When you are unsure, print what you read and check it:
int n;
cin >> n;
int a, b;
cin >> a >> b;
cout << "n = " << n << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;(input: 5\n3 4) n = 5 a = 3 b = 4
Delete those printing lines once you are satisfied. On the judge they are extra output, and they will turn a correct answer into a wrong one.