1

The getline function works in the first iteration of the do-while loop and allows the user to enter their name and outputs this name. When the user enters 'y' the do while loop runs again but does not allow the user to enter their name, it just skips over the getline function as if it isn't there. I used the getline function instead of cin because the user must enter a full name which includes spaces(blank characters).

I've moved the initialization statement of userName into the loop but it didn't help.

#include <iostream>
using namespace std;

int main() {
  string userName = "";
  char response; 

  do
  {
    cout << "Enter a name: ";
    getline(cin, userName);

    cout << userName << endl;

    cout << "You wanna carry on? ";
    cin >> response;
    cin.ignore(1, '\n');
  }while(response == 'y');   

  return 0;
}

I want this code to allow the user to input their name with spaces in every iteration of the do-while loop.

SOLUTION The solution that i have come to is this, i added cin.ignore(1, '\n') just before the end of the do-while loop. This ignores the newline character that the getline function adds to the string.

0 Answers0