Archived

This topic is now archived and is closed to further replies.

hawflakes

i dont want the loop to run forever is someone enters a char instead of int

Recommended Posts

how do i fix this so that if the user enters a letter, it wont go nuts? int aNumber; do { cout << "Enter a number between 1 and 3: "; cin >> aNumber; } while (aNumber < 1 || aNumber > 3); if they enter a letter on accidnet, it looks like this: Enter a number between 1 and 3: Enter a number between 1 and 3: Enter a number between 1 and 3: Enter a number between 1 and 3: Enter a number between 1 and 3: Enter a number between 1 and 3: Enter a number between 1 and 3: Enter a number between 1 and 3: Enter a number between 1 and 3: Enter a number between 1 and 3: Enter a number between 1 and 3: Enter a number between 1 and 3: Enter a number between 1 and 3: Enter a number between 1 and 3: etc. thanks! [edited by - hawflakes on May 3, 2003 3:38:35 PM]

Share this post


Link to post
Share on other sites

int aNumber;

do
{
    std::cout << "Enter a number between 1 and 3: ";
    while (!(std::cin >> aNumber))
    {
        std::cin.clear();
        while (std::cin.get() != '\n')
            continue;

        std::cout << "Enter a number between 1 and 3: ";
    }
}
while (aNumber < 1 || aNumber > 3);


[ Google || Start Here || ACCU || MSDN || STL || GameCoding || BarrysWorld || E-Mail Me ]

[edited by - Lektrix on May 3, 2003 3:53:00 PM]

Share this post


Link to post
Share on other sites