[Solved] Why doesn’t this loop want to work properly?


When you do cin >> divers; the end-of-line character is not removed from the input, just the number leading up to it. Then, the next time you ask for a line with std::getline() it returns just the end-of-line character that is already there and does not wait for your new input.

So when you do cin >> drivers style input before a std::getline() style input you need to read past the end-of-line character.

One way to do that is using the ignore() function:

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

    cout << "Please enter divers name: ";
    getline(cin, name);
    cout << "Enter the diver's city: ";
    getline(cin, city);

    // ...

Another way is to use the white-space eater std::ws in your std::getline() calls:

do{
    cout << "Please enter divers name: ";
    getline(cin >> std::ws, name);
    cout << "Enter the diver's city: ";
    getline(cin >> std::ws, city);

    // ...

Strictly speaking only the first one is necessary. Remember the white-space eater will eat all the initial spaces you type into the getline() so you can’t read in leading spaces if you use that technique.

1

solved Why doesn’t this loop want to work properly?