Question

I have the following function:

void playersetup(string &name){
    char verify;  
    cout<<"Enter player name: ";
    getline(cin,name);
    cout<<endl<<"Your name is: " + name + ", is that correct? (Y for yes, any other key for no): ";
    cin>>verify;
    if ((verify=='y')||(verify=='Y')) {
        verify=='n';
    } else {
        playersetup (name);
    }
}

It asks for the player's name, asks the user to verify thats the name they intended, if not it calls itself to start over. However this is what the output looks like:

Enter Player Name:

user enters: John Smith

Your name is: John Smith, is that correct? (Y for yes, any other key for no):

user enters: n

Enter Player Name:

(user is not given a chance to input anything)

Your name is: , is that correct? (Y for yes, any other key for no):

Is there logic error here or an aspect of getline(cin) that Im missing?

Was it helpful?

Solution

The newline character remains in standard input as the >> char consumes the users single character response only. When std::getline() is next invoked it reads the newline character; a blank line. Consume, or skip, the newline character before asking the user for the name again:

#include <limits> // for 'std::numeric_limits'

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')

OTHER TIPS

If you're using std::getline after std::cin >> verify you need to flush the newline '\n' out of the buffer in between. Otherwise getline reads '\n' and returns. You can add a call to std::basic_istream::ignore to ignore '\n':

#include <limits>

cin>>verify;
cin.ignore ( std::numeric_limits<std::streamsize>::max(), '\n');

basic_istream/ignore

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top