How to use cin in C++?
In C++, cin is an object used to read user input from the standard input stream, typically the keyboard. Here is how cin is used:
- Include the header file: #include
- To declare a variable: It is usually necessary to first declare a variable to store the user input value.
- Declare a variable called “num”.
- Read input: Use the >> operator to store the value entered by the user into a variable.
- Input the value into ‘num’ using ‘std::cin’.
- Note: The >> operator will skip spaces and line breaks until it encounters a non-empty character.
- It is possible to read multiple input values consecutively and store them in different variables.
- Get two numbers, num1 and num2, from the user using std::cin.
- Use the appropriate input operator for different data types.
- Input an integer, a float, and a character using the standard input stream.
- If the value entered by the user does not match the variable type, it will result in input error.
- int num;
std::cin >> num; // User input “abc”
// Error: the input is not an integer, causing the read to fail. - You can use cin.fail() to check for input errors.
- Read in an integer from standard input and store it in a variable called ‘num’. If there is a failure in reading the input, handle the error accordingly.
It is important to note that cin by default uses spaces, tab characters, or newline characters as separators for input values. If you need to read string with spaces, you can use the cin.getline() function or std::getline() function. Additionally, cin can also be used with other input streams in the C++ standard library, such as file streams.