Step 2 of 7
Reading with cin
Input works the same way in reverse: std::cin is the standard input stream, and >> reads a value from it into a variable.
#include <iostream>
#include <string>
int main() {
std::string city;
int year;
double temp;
std::cin >> city >> year >> temp;
std::cout << city << " in " << year << ": " << temp << " degrees\n";
}
Oslo 2024
-3.5
Oslo in 2024: -3.5 degrees
Compared with scanf
- No
&:>>takes its argument by reference (you'll learn references in the next module), so it can fill the variable directly. - No format specifiers: the variable's type decides how the text is parsed. Reading into an
intparses a number; reading into astd::stringreads a word. - Like
scanf,>>skips whitespace before each value, so values can be separated by spaces or newlines.
std::string
std::string (from <string>) is C++'s real string type. It grows automatically as needed, knows its own length, and frees its memory when it's no longer used. No fixed-size arrays, no '\0' bookkeeping, and no buffer overflows when a user types a long name. Reading into it with >> reads one word (up to the next whitespace).
If a read fails (say, letters where an int was expected), the stream goes into a fail state and further reads do nothing. if (std::cin >> x) checks whether a read worked, like checking scanf's return value.
Your task
Read a name and a number of kills and print NAME got N kills.
Challenge 2
Read two whole numbers and print their sum. Input 18 7 prints 25.
Challenge 3
The input is pairs of name kills until the end. Print the player with the most kills (the first one on a tie) as MVP NAME KILLS. Input rain 18 ropz 25 broky 25 prints MVP ropz 25.