Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Problem with getline() after cin >>

  • Difficulty Level : Basic
  • Last Updated : 25 Feb, 2021

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++




// C++ program for the above problem
#include <iostream>
using namespace std;
  
// Driver Code
int main()
{
    int fav_no;
    string name;
  
    cout << "Type your favorite number: ";
  
    // The cin statement uses the
    // fav_no and leaves the \n
    // in the stream as garbage
    cin >> fav_no;
  
    cout << "Type your name : ";
  
    // getline() reads \n
    // and finish reading
    getline(cin, name);
  
    // In output only fav_no
    // will be displayed not
    // 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++




// C++ program for the above solution
#include <iostream>
using namespace std;
  
// Driver Code
int main()
{
    int fav_no;
    string name;
    cout << "Type your favourite number: ";
    cin >> fav_no;
  
    cout << "Type your name: ";
  
    // Usage of std::ws will extract
    // all  the whitespace character
    getline(cin >> ws, name);
  
    cout << name
         << ", your favourite number is : "
         << fav_no;
    return 0;
}

Output:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!