Saturday, May 22, 2010

C++ question?

I need to make this program accept only numbers. No symbols or letters may be used. What can I set the inputNum[i] to that will allow only whole numbers to be inserted and accepted?





cout %26lt;%26lt; "\nPlease enter a whole number: ";


cin %26gt;%26gt; inputNum[i]; //will not function properly.


if (i != ??????????? %26lt;%26lt;%26lt;%26lt;%26lt;%26lt;------THIS IS MY PROBLEM


{


cout %26lt;%26lt; "\nThe number is valid: " %26lt;%26lt; endl;


}


else


{


cout %26lt;%26lt; "\a" %26lt;%26lt; endl;


exit (0);


}

C++ question?
No matter what you do, when you read the line in, it will be a string of characters. The numbers 0 - 9 are the ascii codes 048 - 057.





You need to check to make sure that each char in the string is between 48 and 57.





Your other option is to use the built in atoi() function in a try block. If it fails and you get to the catch block, you know it isn't a number.
Reply:By "whole", I assume you mean natural.





So... all you have to do is verify that each character is a digit:





std::string str;


std::cout%26lt;%26lt;"Enter a whole number: ";


std::cin%26gt;%26gt;str;





for( int i = 0; i %26lt; str.length(); i++ )


{


if( !(str[i] %26gt;= '0' %26amp;%26amp; str[i] %26lt;= '9') )


{


// Invalid input


exit(0);


}


}





// The input is valid
Reply:if u use an integer array, even if someone enters a real number, the number saved will be a whole number only.. for eq. 4.2 will be saved as 4.


i suggest u take it as a float array.. put a check whether the number entered is a whole number or not.. in that way, even if the user enters a real number, u can prompt the user to enter a whole number again and proceed with the program only until he enters a whole number...


No comments:

Post a Comment