0
using namespace std;

int main()
{
    char repeat;
    do
    {
        string str;
        cout << "What is your first and last name? " << endl;
        getline(cin, str);

        string findSpace = " ";
        int found = str.find(findSpace) + 1;

        cout << str[0] << str[found] << endl;

        cout << "repeat? " << endl;
        cin >> repeat;

    } while (repeat == 'y');
    
}

I have this code that helps me get the initials of the first and last name. But when I go to repeat the code it automatically couts "What is your first and last name?" as well as "repeat?". It won't go through the steps of asking for the first and last name, giving the initials, and then asking if the user wants to repeat.

What am I doing wrong here?

Puggy
  • 107
  • 1
  • 6
  • 3
    `cin >> repeat;` leaves the `'\n'` in the buffer, when you press `y`. You have to remove it before continuing. – mch Dec 06 '22 at 10:48
  • 2
    A side note: better to avoid `using namespace std` - see here https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice. – wohlstad Dec 06 '22 at 10:53
  • 1
    Does this answer your question? [Why does std::getline() skip input after a formatted extraction?](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction) – bitmask Dec 06 '22 at 10:59

1 Answers1

0
using namespace std;

int main()
{
    char repeat;
    do
    {
        string str;
        cout << "What is your first and last name? " << endl;
        // 
        getline(cin >> ws, str);

        string findSpace = " ";
        int found = str.find(findSpace) + 1;

        cout << str[0] << str[found] << endl;

        cout << "repeat? " << endl;
        cin >> repeat;

    } while (repeat == 'y');
    
}

Thanks to the comment by mch I've solved it. This is my solution.

Puggy
  • 107
  • 1
  • 6