<ch************@gmail.com> wrote in message
news:11**********************@g44g2000cwa.googlegr oups.com...
I am having trouble understanding why the code given belows enters an
infinite loop when a char is entered instead of an int.
i.e.on subsequent looping ,control doesn't wait for user input and just
keeps printing "Hello" infinitely.
#include<iostream>
using namespace std;
int main()
{
int ch;
while(1)
{
cout<<"Hello";
cin>>ch;
cout<<"You entered "<<ch<<endl;
if(ch==1)
break;
}
return 0;
}
The main problem is your test:
if(ch==1) break;
That will only be true if the character the user enters has
ascii code 1, which is the "SOH" control character. That's
not on any keyboard. There's no such key. Hence, infinite
loop. (Well, the user might be able to break from the loop
by pressing ALT-0-0-0-1, but not many users would have the
gumption to do that.)
I think what you really want is:
if ('1' == ch) break;
NOTE THE SINGLE QUOTES AROUND THE '1'. That indicates
"the character '1' " rather than "the character whose ascii
code is 1".
--
Cheers,
Robbie Hatley
Tustin, CA, USA
email: lonewolfintj at pacbell dot net
web: home dot pacbell dot net slant earnur slant
----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----