In this C++ tutorial, you will learn how to read input from user using cin object, with examples.
C++ cin
cin object along with extraction operator >>
is used to read input from user via standard input device. cin is predefined object in istream.h and is linked to standard input.
To use cin object in your program, include iostream.h and use std namespace.
Read integer from user
In the following example, we shall read integer from user using cin object.
C++ Program
#include <iostream>
using namespace std;
int main() {
int x;
cout << "Enter a number : ";
cin >> x;
cout << "You entered a number : " << x << endl;
}
Output
Enter a number : 63
You entered a number : 63
Read string from user
In the following example, we shall read a string from user using cin object. cin reads string until the occurrence of a space character.
C++ Program
#include <iostream>
using namespace std;
int main() {
string name;
cout << "Enter a string : ";
cin >> name;
cout << "You entered a string : " << name << endl;
}
Output
Enter a string : tutorialkart
You entered a string : tutorialkart
Read double value from user
In the following example, we shall read a double from user using cin object.
C++ Program
#include <iostream>
using namespace std;
int main() {
double d;
cout << "Enter a double value : ";
cin >> d;
cout << "You entered : " << d << endl;
}
Output
Enter a double value : 1.32654663
You entered : 1.32655
Read char from user
In the following example, we shall read char from user using cin object.
C++ Program
#include <iostream>
using namespace std;
int main() {
char ch;
cout << "Enter a character : ";
cin >> ch;
cout << "You entered : " << ch << endl;
}
Output
Enter a character : m
You entered : m
Read boolean from user
In the following example, we shall read boolean value from user using cin object.
C++ Program
#include <iostream>
using namespace std;
int main() {
int x;
cout << "Enter a number : ";
cin >> x;
cout << "You entered a number : " << x << endl;
}
Output
PS D:\workspace\cpp> .\main.exe
Enter a boolean value : 1
You entered : 1
PS D:\workspace\cpp> .\main.exe
Enter a boolean value : 4
You entered : 1
PS D:\workspace\cpp> .\main.exe
Enter a boolean value : -9
You entered : 1
PS D:\workspace\cpp> .\main.exe
Enter a boolean value : 0
You entered : 0
PS D:\workspace\cpp> .\main.exe
Enter a boolean value : -25
You entered : 1
Any positive or negative value is considered true, and the value read to boolean variable is 1
.
Zero is considered false and the value read to boolean variable is 0
when user inputs 0
.
Conclusion
In this C++ Tutorial, we learned how to use cin object to read input from user.