• Advertisement

Archived

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

Simple input problem

This topic is 5306 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

here''s the code: void TavernOptions() { int option; // For user input // cout << endl << "What would you like to do?" << endl << "1) Talk to the barkeep 2) Talk to the barmaid 3) Talk " << "to the man in the shadows\n" << "4) Exit the tavern 5) See more options. "; cin >> option; switch(option) { case 1: cout << endl << "You talk to the barkeep" << endl; break; case 2: cout << endl << "You sit and talk to the barmaid" << endl; break; case 3: cout << endl << "You talk to the man in the shadows" << endl; break; case 4: cout << endl << "You exit the tavern" << endl; break; case 5: cout << endl << "You see more options" << endl; break; default: cout << endl << "That is not an option. Please try again." << endl; TavernOptions(); break; } } when the user inputs a character instead of an integer, this thing goes into an endless loop. I''ve tried all kinds of stuff and it appears that when a char is enter, "cin" is totally ignored the next time the function is called. is there anyway around this or maybe a better way to handle bad input? any help would be greatly appreciated.

Share this post


Link to post
Share on other sites
Advertisement
If I understand you correctly, you might want to try replacing this:

std::cin >> option;

with this:

while ( !(std::cin >> option) )
{
    std::cin.clear();
    while ( std::cin.get() != ''\n'' )
        continue;

    std::cerr << "Error: Invalid input." << std::endl;
    std::cout << "Please re-enter option: ";
}

(Sorry, you''ll have to remove all the qualifications (''std::''s) - I''m just used to qualifying. )

[ Google || Start Here || ACCU || STL || Boost || MSDN || GotW || MSVC++ Library Fixes || BarrysWorld || E-Mail Me ]

Share this post


Link to post
Share on other sites
Thanks a lot! I''m new to this and that''s been driving me nuts. Now I just gotta figure out what that stuff means
Thanks again!

Share this post


Link to post
Share on other sites

  • Advertisement