Better way of clearing an input buffer?

49 Views Asked by At

I am learning how to clear an input buffer. So far I have come across two statements that both work and seem to do the same thing:

while(getchar() != '\n');
cin.ignore(numberic_limits<streamsize>::max(), '\n');

Is there any difference for choosing one over the other, besides the fact that the second is more typing and requires that you include an additional header file?

Here is the first program I ran. At the first prompt, I entered "Sandy askdjfhlaf". At the second prompt, I entered "Cheeks".

#include <iostream>
#include <string>

using namespace std;

int main(){
    
    string first_name;
    string last_name;
    
    cout << "First name: ";
    cin >> first_name;
        
    while(getchar() != '\n'); // the statement in question    
    
    cout << "Last name: ";
    cin >> last_name;
    
    cout << first_name << ' ' << last_name;
    
    return 0;
}

The output was:

Sandy Cheeks

Here is the second program I ran. I tested this second program with the same input:

#include <iostream>
#include <string>
#include <limits>

using namespace std;

int main(){
    
    string first_name;
    string last_name;
    
    cout << "First name: ";
    cin >> first_name;
    
    cin.ignore(numeric_limits<streamsize>::max(), '\n'); // the statement in question    
    
    cout << "Last name: ";
    cin >> last_name;
    
    cout << first_name << ' ' << last_name;
    
    return 0;
}

I expected the program to either behave differently than the first program, or to produce different output. However, the result appeared to be identical.

0

There are 0 best solutions below