Taking User Input:
We have already studied about the use of cout object along with the insertion operator. It is used to print string/text (sequence of characters like "My age is 20.") as well as variables on screen.
For taking input from user, we use cin object along with extraction operator.
>>
cin is pronounced as "see-in"
Point : When we are taking input from the user, we store it in a variable.
input.cpp
#include <iostream>
using namespace std;
int main(){
int num;
cout<<"Write a number\n"<<endl;
//after writing value press enter
cin >> num;
cout << "Value of a is " << num << endl;
return 0;
}
- We use insertion operator after cout.
- cout is used for printing.
- We use extraction operator after cin.
- cin is used to take user input.
Taking Input from the User:
In the given C++ program, we wre taking input in different types of variables.input.cpp
#include <iostream>
using namespace std;
int main(){
string name;
int age;
double height;
// Taking input in string type variable
cout << "Enter your name "<<endl;
cin>>name;
// Taking input in int type variable
cout << "Enter your age "<<endl;
cin>>age;
// Taking input in double type variable
cout << "Enter your height "<<endl;
cin>>height;
cout << "Name is "<< name << endl;
cout << "Age is "<< age << endl;
cout << "Height is "<< height << endl;
return 0;
}
Building a simple calculator:
input.cpp
#include <iostream>
using namespace std;
int main(){
int num1, num2;
cout<<"Enter first number \n";
cin>>num1;
cout<<"Enter second number \n";
cin>>num2;
int sum, diff, quotient, product;
sum = num1+num2;
diff = num1-num2;
quotient = num1/num2;
product = num1*num2;
cout<<"Sum is "<<sum<<endl;
cout<<"Difference is "<<diff<<endl;
cout<<"Quotient is "<<quotient <<endl;
cout<<"Product is "<<product<<endl;
return 0;
}