C++ Strings: User Input

User Input Strings

It is possible to use the extraction operator >> on cin to display a string entered by a user.

Example:1
string n;
cout<<“Enter any string “;
cin>>n;
cout<<“String is “<<n<<endl;

Output:
Enter any string hello
String is hello

#include<iostream>
#include<string>
using namespace std;
int main()
{
	string n;
	cout<<"Enter any string ";
	cin>>n;
	cout<<"String is "<<n<<endl;
	return(0);
}

Note:When we take input using cin it does not take input after spaces.

Example:2
string n;
cout<<“Enter any string “;
cin>>n;
cout<<“String is “<<n<<endl;

Output:
Enter any string hello
String is hello

Example:2
string n;
cout<<“Enter any string “;
cin>>n;
cout<<“String is “<<n<<endl;

Output:
Enter any string hello world
String is hello

#include<iostream>
#include<string>
using namespace std;
int main()
{
	string n;
	cout<<"Enter any string ";
	cin>>n;
	cout<<"String is "<<n<<endl;
	return(0);
}

getline() : This functions helps us to take input for a string with spaces.

Syntax:
string n;
cout<<“Enter any string “;
getline(cin,n);

#include<iostream>
#include<string>
using namespace std;
int main()
{
	char n[20];
	cout<<"Enter any string ";
	cin.getline(n,20);
	cout<<"String is "<<n<<endl;
	return(0);
}
#include<iostream>
#include<string>
using namespace std;
int main()
{
	string n;
	cout<<"Enter any string ";
	getline(cin,n);
	cout<<"String is "<<n<<endl;
	return(0);
}