Home > Mobile >  While loop repeats for every word in a string in C
While loop repeats for every word in a string in C

Time:11-29

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 ?

CodePudding user response:

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;
}
  • Related