In c++, many a times, you’d want to take a string as an input. But the default cin statement cannot accept spaces, i.e. it terminates the input when it encounters a space. For eg, if you input ‘Hello World’, only ‘Hello’ would be stored and rest all discarded. To overcome this, we have a function called cin.getline().
#include <iostream>
using namespace std;
int main()
{
char stn[20];
cin.getline(stn,20);
cout<<stn;
system("PAUSE");
return 0;
}
The cin.getline() function accepts two parameters, one is the variable where the input would be stored, and second is the maximum input length.
Lets dissect the above code,
- First, we declare a variable stn to store a string of maximum length 20.
- We use the cin.getline() function, with the first parameter as our declared variable stn and second parameter as the maximum length that stn can hold, i.e 20.
- Remember, for example if you specify the length as 5, only a maximum of 4 characters would be taken as input from the user, even if he exceeds this limit. This is because the 5th place is used to store the null terminator.
Thus, the function is quite similar to the standard cin function, only that it even allows for spaces.
Have any suggestions or anything to say? Write a comment below!

Hello,
thanks for this short tut, i can use this!
However, I’m not getting something; in your code you write:
cin.getline(s,20);
doesn’t it have to be:
cin.getline(stn,20);
I’m confused
Thank you,
Thomas.
Hi Thomas,
Yes, it has to be stn. Actually, I had changed the ’s’ to ’stn’ for better readability, but forgot to change it inside the getline function. I’ve updated the post.
Thanks for the reply again!
Thanks im new to cpp and this was quite useful.