I wrote a program too convert a 4 digit positive octal number too its decimal equivalent. However while trying too validate the user input(0-7) a problem occured. Within my for loop too prevent the user entering 8 or 9, when i input numbers that should be allowed, the program still terminates and displays, "You entered a number above 7".
Not sure what i've done wrong, any help would be appreciated. Here is the code that is having problems.
int main()
{
//declare variables
int i, octNum = 0, decNum = 0, arr[20];
//get octal value from user input
cout << "Enter the 4 digit Octal Number you would like too convert: " ;
cin >> octNum;
// validate input if value is negative, or greater then 4 digits
if(octNum < 0)
{
cout << "Please enter a positive octal number from 0-7\n";
return 0;
}
else if(octNum > 7777)
{
cout << "Please enter a 4 digit octal number from 0-7 only\n";
return 0;
}
// Validate for octal digits 0-7. If 8 or 9 prompt user too start again
for(int n = 0; octNum > 0; n++)
{
if(n == 8 || n == 9)
{
cout << "One of the numbers was above 7 \nPlease enter an octal number from 0-7\n";
return 0;
}
}
I assume you meant something like this:
for(int n = octNum; n > 0; n /= 10)
{
if ((n % 10) > 7)
{
cout << "One of the digits was above 7\nPlease enter a valid octal number" << endl;
return 0;
}
}