How to get inputs from the user in c++ ?
Inputs are the important in any programming language. For any language, the processing and outputs are based on the input only.
In c++, there are two ways to get the input as follows…
1. 'cin’ method
2. 'getline()’ method
Each one is built-in functions in c++.
1. ‘cin’ method:
This method
is included in iostream header file. It reads the input from the user directly.
Syntax : cin>> variable name;
Eg: cin>> name;
Let us create a c++ program to get the input and print it.
C++ program:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int n;
char a;
string name;
float no1;
cout<< "Enter the number :";
cin >> n;
cout << "Enter the character :"
<<endl;
cin >> a;
cout << "Enter the float number :"
<<endl;
cin >> no1;
cout <<"Enter the name :" <<endl;
cin >> name;
cout << "The values are:" <<endl;
cout <<
"Number:" << n <<endl;
cout << "Character :" << a
<<endl;
cout << "Name: " << name <<endl;
cout << "Float number: " << no1
<<endl;
return 0;
}
Output:
Enter the
number :23 Enter the
character : s Enter the
float number : 45.78 Enter the
name : jeyanth |
The values
are: Number:23 Character :s Name: jeyanth Float number:
45.78 |
2.‘getline()’ function:
If you
want to read the entire input line with spaces. This is the function you need.
Here is the program to display greetings.
C++ program:
#include <iostream>
#include <string>
using namespace std;
int main() {
string a;
cout <<
"Enter the wishes: ";
getline(cin,
a); // Reads a full line of input
cout << a
<<"!!";
return 0;
}
Output:
Enter the wishes: Have a nice day
Have a nice day!!
Hope, these two methods are useful to you. Keep Coding!!!
Comments
Post a Comment