Connecting Tech Pros Worldwide Forums | Help | Site Map

Unexpected result when entering wrong data type

japh
Guest
 
Posts: n/a
#1: Jul 23 '05
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


David Hilsee
Guest
 
Posts: n/a
#2: Jul 23 '05

re: Unexpected result when entering wrong data type


"japh" <japh@eudoramail.com> wrote in message
news:1105213401.397695.92980@c13g2000cwb.googlegro ups.com...[color=blue]
> 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 ?)[/color]

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.

--
David Hilsee


Victor Bazarov
Guest
 
Posts: n/a
#3: Jul 23 '05

re: Unexpected result when entering wrong data type


"japh" <japh@eudoramail.com> wrote...[color=blue]
>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.[/color]

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.
[color=blue]
> 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 ?)[/color]

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.
[color=blue]
> [...][/color]

V


japh
Guest
 
Posts: n/a
#4: Jul 23 '05

re: Unexpected result when entering wrong data type


OK - thanks... will do

japh
Guest
 
Posts: n/a
#5: Jul 23 '05

re: Unexpected result when entering wrong data type


thanks

Closed Thread


Similar C / C++ bytes