Here is a small piece of code to show you how it exactly works. We will simply take input of a string using cin and then show this input to the output stream and will learn how cin works.
#include<conio.h>
#include<iostream.h>
void main()
{
char inString[50];
cout<<"Type a string: ";
cin>>inString;
cout<<"The input is: "<<inString<<endl;
getch();
}
Output:
| Click to Enlarge |
The output shows that cin only keeps the first word and ignores the rest.
The Other Method:
Here is another way to get input in C Plus Plus from the user. We can do it using getline keyword. The method is still so simply but slightly different.
How getline Works?
getline gets input and keeps the whole input without ignoring any words or spaces. Here is a small piece of code similar to previous one, but we will be using getline for taking input along with the previous keyword cin.
#include <iostream>
using namespace std;
int main()
{
string inString;
cout<<"Type a String: ";
getline(cin, inString);
cout<<"The input is: "<<inString<<endl;
return 0;
}
Note: I have tested this code in "Eclipse" IDE. And it works fine in it. This code may not work properly in many other IDE's. You will have to set-up some configurations of your IDE.
Output:
| Click to Enlarge |
The output clearly indicates that getline keeps the whole string that was input in it without wasting or ignoring a single character.
No comments:
Post a Comment