The getline() function in C++ is used to read a string or a line from the input stream. The getline() function does not ignore leading white space characters. So special care should be taken care of about using getline() after cin because cin ignores white space characters and leaves it in the stream as garbage.
Program 1:
Below is the C++ program to illustrate the same:
C++
#include <iostream>
using namespace std;
int main()
{
int fav_no;
string name;
cout << "Type your favorite number: " ;
cin >> fav_no;
cout << "Type your name : " ;
getline(cin, name);
cout << name
<< ", your favourite number is : "
<< fav_no;
return 0;
}
|
Output:

Explanation:
The solution to solve the above problem is to use something which extracts all white space characters after cin. std::ws in C++ to do the same thing. This is actually used with the “>>” operator on input streams.
Program 2:
Below is the C++ program to illustrate the solution for the above problem:
C++
#include <iostream>
using namespace std;
int main()
{
int fav_no;
string name;
cout << "Type your favourite number: " ;
cin >> fav_no;
cout << "Type your name: " ;
getline(cin >> ws, name);
cout << name
<< ", your favourite number is : "
<< fav_no;
return 0;
}
|
Output:
