The std::cin
object in C++ is a fundamental tool for reading input from the standard input, typically the keyboard. It is part of the standard library and resides in the std
namespace.
To use std::cin
, include the <iostream>
header at the beginning of your code:
#include <iostream>
The extraction operator, >>
, is used to read data from std::cin
. For example:
int x;
std::cin >> x;
This reads an integer from the standard input and stores it in the variable x
.
std::cin
can read various data types. For example:
std::string name;
std::cin >> name;
This reads a string from the input and stores it in the variable name
. However, it stops reading at the first whitespace. To read a full line including spaces, use the getline()
function:
std::string line;
std::getline(std::cin, line);
Multiple >>
operators can be chained to read multiple variables in a single line. For example:
int a, b;
std::cin >> a >> b;
This reads two integers from the input and stores them in a
and b
, respectively.
Avoid using namespace std;
to prevent namespace pollution. Instead, use the std::
prefix or selective using
declarations.
std::cin
reads input from the standard input by default, which is typically the keyboard. It can also be redirected to read from files or other sources.
<iostream>
header, which is necessary to use std::cin
.std::cin >>
to read strings that contain spaces, as it stops reading at the first whitespace. Use std::getline()
for such cases.std::cin
is essential for basic input operations in C++. Understanding its syntax, usage, and potential pitfalls enhances program functionality and robustness.