I just started C++ programming. As I was trying to:
Determine the biggest number entered by user using while loop. Everything works fine, but I realize that the user could always enter an alphabet letter. That was when the idea of using isalpha function comes to mind.
You can't use isalpha in this manner. It is only good for the range of char, not int. If a value greater (or less than) that capable of being held by char is entered, you enter the world of undefined behavior.
When you do cin >> i where i is of type int and cin encounters non-numbers in the input stream it does not extract that input from the stream. After all, you're asking for an int, not anything else. What it does do is go into an error state.
int largest = std::numeric_limits<int>::min() ;
int smallest = std::numeric_limits<int>::max() ;
bool gettingInput = true ;
while ( gettingInput )
int i ;
std::cout << "Please enter an integer\n" ;
while ( !(std::cin >> i) )
std::cout << "Invalid input. Please enter an integer\n" ;
// clear error state and extract the unwanted stuff from the stream:
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n' ) ;
if ( i < 0 )
gettingInput = false ;
if ( largest < i )
largest = i ;
if ( smallest > i )
smallest = i ;
std::cout << "Largest entered: " << largest ;
std::cout << "\nSmallest entered: " << smallest << '\n' ;
Thanks man for the quick reply !!! That really clear things up.
I am not familiar with cin. To clear things up, I have a few questions:
You're using cin.ignore() to remove any error char in the stream right ? The clear is to flush away any error from the input or EOF.
Another thing, I realized that most code samples did not use the "using namespace std".
Why do people tend to use the scope resolution operator instead ? Does the using directive causes a particular overhead on my program ? I am just curious.
Well when you include usingnamespace std; you are adding in a whole bunch of things you mainly never will use in your program. So generally people will do this, they will use using std::cout; when they intend to use cout frequently, and for other things they will only use once in a while they will do std::endl;.
While you are just learning to program in C++ it is perfectly fine to use namespace std; in your programs, but when you do start to produce stuff that is going to be released to other people it is generally a bad thing to do, because of the overhead it produces and it sometimes clashes with other libraries.