i'm trying to validate numbers as I enter them in my program. can anyone tell me whats wrong with this?
cout %26lt;%26lt; "\nHow many whole numbers (up to 20) would you like to organize? ";
cin %26gt;%26gt; numberNum;
if (numberNum != '0','1','2','3','4','5','6','7','8','9' )
{
cout %26lt;%26lt; "Please enter a valid number: " %26lt;%26lt; endl;
}
everytime i run the program, the message pops up. its as if the compiler sees the valids "1,2,3..." as invalid. any suggestions?
Validating crap in c++?
why don't u try this
cout %26lt;%26lt; "\nHow many whole numbers (up to 20) would you like to organize? ";
cin %26gt;%26gt; numberNum;
if (numberNum %26gt; 20 || numberNum %26lt;0)
{
cout %26lt;%26lt; "Please enter a valid number: " %26lt;%26lt; endl;
cin %26gt;%26gt; numberNum
}
Reply:The comma is a valid C++ operator, but it doesn't do what you're thinking it does. The comma evaluates the expression on its left, discarding the result, then returns the type and value of the expression on the right. Also, you're making your life difficult. For 0-20, it's difficult, but what if you wanted the numbers 0-100 to be valid?! Typing them all out would get insane, and a phone number, a MILLION possible numbers you don't want to type!
use if(numberNum %26gt;= 0 %26amp;%26amp; numbernNum%26lt;=20)
now if you want to expand it to a million all you have to change it to would be
if(numberNum %26gt;= 0 %26amp;%26amp; numberNum%26lt;= 10000000)
(you'd also have to make it an integer, but a search of answers will tell you how to do that).
Reply:instead you need this...
if (numberNum != '0' %26amp;%26amp; numberNum != '1' %26amp;%26amp; numberNum != '2') //etc
Perhaps a better way to ensure the validity of the input is to get it as a string using getline, then pass it to a function like atoi() and check for an error.
Reply:This only checks 0. You need :
if ((numberNum %26gt;-1) %26amp;%26amp; (numberNum %26lt;20)
{//routine for a match
}else
{//routine for no match
}
Reply:"numberNum != '0','1','2','3','4','5','6','7'..." is not valid.
You would need to do this: "numberNum != '0' %26amp;%26amp; numberNum != '1' %26amp;%26amp; numberNum != '2'..."
Otherwise, instead of using cin, do this:
int numberNum;
scanf(%d , %26amp;numberNum ); //read in the value as an integer
if( numberNum %26lt; 0 || numberNum %26gt; 20) {
....
}
apple
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment