C++ cin Tutorial
Syntax
The cin
statement in C++ is used to read input values from the standard input stream. The syntax for using cin
is:
cin >> variableName;
where variableName
is the name of the variable that will store the input value.
Example
#include <iostream>
using namespace std;
int main() {
int num1, num2;
cout << "Enter two integers: ";
cin >> num1 >> num2;
cout << "Your input values are: " << num1 << " and " << num2;
return 0;
}
Output
The output of the above program will be:
Enter two integers: 10 20
Your input values are: 10 and 20
Explanation
In the above example, we have declared two integer variables num1
and num2
. We then prompt the user to enter two integers by displaying the message "Enter two integers: " on the console. We then use the cin
statement to read the input values from the user and store them in the two variables num1
and num2
. Finally, we display the values of num1
and num2
to the user on the console.
Use
cin
is mainly used for accepting input values from the user during runtime. It is generally used in combination with cout
for taking input from the user and displaying output on the console.
Important Points
- The
>>
operator is used to extract data from the input stream. - When
cin
is used for accepting string inputs, the strings are stopped at the first white space encountered. cin
can be used with any data type, such as integers, character data types, and strings.
Summary
cin
is an integral part of C++ programming, as it reads input values during runtime. Its syntax is straightforward, and it can be used to read input data of all data types. It is an excellent tool for user interaction and overall program functionality.