HELP-- getline() function's drawback- NEED HELP!

Hey coders, I am having a problem using getline() , below is the problem example and the problem is described in the o/p section.

using namespace std;

int main()
{
string name;
int id;

// Taking id as input 
cin >> id; 

// Takes the empty character as input 
getline(cin, name); 

// Prints id 
cout << "Your id : " << id << "\n"; 

// Prints nothing in name field 
// as "\n" is considered a valid string 
cout << "Hello, " << name 
     << " welcome to GfG !\n";

return 0; 

}

INPUT
7
MOHIT KUMAR

OUTPUT
Your id : 7
Hello, welcome to GfG ! //Here is the problem, I want ‘MOHIT’ here before ‘welcome’;

Currently the name variable is storing an empty string bcz ‘\n’ is going as input in the variable immediately, and we know that getline() assumes ‘\n’ as delimeter

So I wanna ask you guys that how can I take ‘MOHIT’ in variable ? without taking this empty string as i/p.

Thanks in advance !!!

[https://www.geeksforgeeks.org/getline-string-c/](http://getline() link) for reference

we have to clear the input buffer . so we can use cin.ignore( ) function for C++ .

1 Like

so just use the cin.ignore( ) function u will get the required output besides this i will give u a standard problem in codechef which uses this concept and I also got stuck in it when i was a beginner.

1 Like