Monday, 10 March 2014

getline: Another Method of Taking Input in C Plus Plus

In previous lessons we have learn that the keyword cin is used to get input from the user. But I want to tell you something about cin keyword that is very important to know. The keyword cin separates the words or "group of characters differentiated by spaces". It only keeps the first group of characters (or first word) and ignores the rest of the characters coming after the space.

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:

Input using cin and show it as 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:

Input using getline and show it as 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