Click here to Skip to main content
15,891,423 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I dont understand what happened to (cin), see my code:
C++
#include <iostream>
int main()
{
	 int num;
	 do
	 {
		 cout<<"sdjlsdklsdf";
		 cin >>num;
	 }while (num!=100);

return 0 ;
}

If a number is entered, the program run fine. But the problem happens when a character is entered, try it your self.
The (cin) stop functioning!!.

Anyone has any idea?
Posted
Updated 5-Mar-11 0:09am
v2

cin is working properly, of course. Your code , on the other hand, wrongly assumes that input operation was successfully completed. Try this fix:
C++
#include <iostream>
using namespace std;
int main()
{
     int num;
     do
     {
         cout<<"sdjlsdklsdf";
         cin >>num;
     if (! cin.good()) break;
     }while (num!=100);

return 0 ;
}
 
Share this answer
 
Comments
Andrew Brock 5-Mar-11 7:56am    
LOL! 5.
CPallini 5-Mar-11 8:28am    
Why thank you, sir. :-)
Sergey Alexandrovich Kryukov 5-Mar-11 23:54pm    
I just imagined what OP expected (see my comment below :-) :-))
--SA
Abudreas 5-Mar-11 9:55am    
thank you for help.but as i know (char) data type is smaller than (int) (char = 8bit,int=32bit). so you don't need any extra work to convert from (char) to (int).
still i don't understand what the problem.
CPallini 5-Mar-11 10:22am    
The cin.good() returns false because the conversion of a string (e.g. "W" or "zass") to a number fails (cin takes a string from the console and tries to convert to a number). That's has nothing to do with char and int sizes.
Looks like 'num' is declared an integer and so until unless you enter a number it does not move ahead.

Give your cout message properly that one needs to input a number to move ahead.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900