Unexpected result when entering wrong data type

J

japh

I am on chapter 7 of my C++ text (sigh). Could you help me understand
this? If the user inputs an int, the script works as it should. If
they enter a char instead, it goes into an endless loop. I'm coming
from un-typed languages like PERL and PHP so this makes no sense to me:
(PS - is there a way to preserve indentation in this bulletin board ?)

#include <iostream>
using namespace std;

int main()
{
while(true)
{
int choice;
cout << endl << "Enter a number between 1 - 5: ";
cin >> choice;

if (choice < 1 || choice > 5)
{
cout << endl << "Invalid choice" << endl;
continue;
}
else
{
cout << "You chose " << choice << endl;
}
}// end while
} // end main
 
V

Victor Bazarov

japh said:
I am on chapter 7 of my C++ text (sigh). Could you help me understand
this? If the user inputs an int, the script works as it should. If
they enter a char instead, it goes into an endless loop.

This is actually a FAQ. Visit http://www.parashift.com/c++-faq-lite/
Read it all when you have time just to get an idea what has already
been answered, so you don't ask about it again (unless it's unclear
or you think it's incorrectly answered there). For now, you need the
section 15.
I'm coming
from un-typed languages like PERL and PHP so this makes no sense to me:
(PS - is there a way to preserve indentation in this bulletin board ?)

Not if you're using Google's delapidated posting service. Get a real ISP
and connect to their news server using a real news reader.

V
 
D

David Hilsee

japh said:
I am on chapter 7 of my C++ text (sigh). Could you help me understand
this? If the user inputs an int, the script works as it should. If
they enter a char instead, it goes into an endless loop. I'm coming
from un-typed languages like PERL and PHP so this makes no sense to me:
(PS - is there a way to preserve indentation in this bulletin board ?)

The FAQ (http://www.parashift.com/c++-faq-lite/) answers this. See section
15 ("Input/output via <iostream> and <cstdio>"), question 2 ("Why does my
program go into an infinite loop when someone enters an invalid input
character?"). The other answers in that section are a good read as well.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top