std::cin#include <iostream> reads user input from standard input. It is a type-safe alternative to C's scanf and is available from the iostream header. Values are read from std::cin#include <iostream> with the extraction operator (>>):
#include <iostream>
int var;
std::cin#include <iostream> >> var;Reads can be chained. >> skips leading whitespace and reads the next token, so values can be separated by spaces, tabs or newlines:
int var1, var2, var3;
std::cin#include <iostream> >> var1 >> var2 >> var3;
// Input: 1 2 3 (works)
// Input: 1\n2\n3 (also works)std::cin#include <iostream> >> var returns the stream, which converts to false when the read fails, such as at the end of input or when the input doesn't match the type. This makes it usable as a loop condition:
int var;
while (std::cin#include <iostream> >> var) {
std::cout#include <iostream> << var << "\n";
}Values of different types are read in the order they appear in the input:
int var;
char ch;
float num;
std::cin#include <iostream> >> var >> ch >> num;
// Input: 10 a 3.14 (works)
// Input: 10a3.14 (also works)Note
>> doesn't need whitespace between values of different types. It stops at the first character that doesn't fit the target type, so in 10a3.14, 10 stops at a, a fills the char, and 3.14 is read as a float.
>> stops at whitespace, reading into a std::string#include <string> reads one word:
std::string#include <string> word;
std::cin#include <iostream> >> word; // hello world -> "hello"std::getline#include <string> reads a whole line:
std::string#include <string> line;
std::getline#include <string>(std::cin#include <iostream>, line); // hello world -> "hello world"
Dan