C/C++ Arena

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

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 turn: read a name and a number of kills and print NAME got N kills.

Previous: Hello, C++ Next: std::string is easy