0

I am trying to make a magic 8 ball that provides a random preset answer to any input except "bye". Each time the void function magic8ball() is called, it generates a random number from 0 - 19 and prints a corresponding response to the console.

int main()
{
    string question;
    cin >> question;
    while (question != "bye") {
        magic8ball(); 
        cout << "~Ask another question.\n";
        cin >> question;
    }
    return 0;
}

For some reason, if the input for question has more than one word / has whitespace between characters, the loop repeats for each word before asking for input again. I stuck a "cout << question << endl;" in there and it showed each word in the string (as well as a call of magic8ball and "ask another"). e.g

>hi frend
 ... Ask again later
hi
~Ask another question.
 ... Don't count on it
frend
~Ask another question.

How do I prevent the while loop from treating the string as a series of words? Why is cin not triggering along with magic8ball() and cout ?

  • 1
    By default `>>` only reads until it encounters whitespace. If you want to read a line you should use `std::getline`. – Retired Ninja Nov 28 '21 at 02:59
  • @RetiredNinja Thanks for your response. `getline(cin, question)` works, but is there a way to do it with `cin >> ` alone? – FredrickVonHumperdinger Nov 28 '21 at 03:06
  • It's better to use the right tool for the job rather than trying to make the wrong one work. When you do you run into problems like this: https://stackoverflow.com/questions/10946771/effect-of-noskipws-on-cin and this: https://stackoverflow.com/questions/21809838/demonstration-of-noskipws-in-c – Retired Ninja Nov 28 '21 at 03:09

1 Answers1

2

std::cin stops reading when it sees whitespace. Space also counts as a whitespace.

If you want your string to have space, use std::getline()

int main()
{
    string question;
    std::getline(std::cin, question);
    while (question != "bye") {
        magic8ball(); 
        cout << "~Ask another question.\n";
        std::getline(std::cin, question);
    }
    return 0;
}