Website For Developers

Input in C++



• The process of putting something in the system (through keyboard, or other device) is called input.
cin stream object is used for input in C++.
• cin stands for Console Input.
• For standard input/output (cin/cout), we use header file iostream.h
• iostream.h contains the declaration of all standard input and output stream objects.
• cin object is used with extraction >> operator.
• getline() is also used for string input.
• getline in C++ reads characters from an input stream and set those character into a string.


Syntax

cin >> variable;
// input with getline function
getline(cin , variable);


Example of input in C++

#include<iostream>
#include<conio.h>
using namespace std;
int main() {
  int a ;
  cout<< "Enter an integer value: ";
  cin>> a; //getting user input
  cout<<"Value: "<< a;
  getch();
  return 0;
}

Output

Enter an integer value: 3
Value: 3


Example of getline in C++

#include<iostream>
#include<conio.h>
using namespace std;
int main() {
  string name;
  cout<< "Enter your name: ";
  getline(cin, name); //getting user input
  cout<<"User name is = "<< name;
  getch();
  return 0;
}

Output

Enter your name: Alex
User name is = Alex


Write a program that get two integer values from user and display the sum of them.

#include<iostream>
#include<conio.h>
using namespace std;
  int main() {
  int a , b;
  cout<< "Enter first value: ";
  cin>> a;
  cout<< endl<< "Enter second value: ";
  cin>> b;
  int sum = a+b; //Adding
  cout<< endl<< "Total is: "<< sum;
  getch();
  return 0;
}

Output

Enter first value: 23

Enter second value: 34

Total is: 57


Write a program that get input from user and then show the output on the screen.

#include<iostream>
#include<conio.h>
using namespace std;
int main() {
   int age ;
   char name[20]; //Character Array
   char fname[20]; //Character Array
   cout<< "Enter Name: ";
   cin>> name;
   cout<< "Enter Father Name: ";
   cin>> fname;

   cout<< "Enter Age: ";
   cin>> age;

   cout<< "User name is "<< name<< " "<< fname<< " and his age is "<< age;
   getch();
   return 0;
}

Output

Enter Name: Tom
Enter Father Name: Hank
Enter Age: 34
User name is Tom Hank and his age is 34