I've been trying to shake some rust doing some basic programming in C++ and trying to get my skills to handle possible errors more efficiently. Anyway, I ran into some weird logic error which I isolated and I think I solved how the program can avoid it, but wanted to know if someone more knowledgeable could find a better solution or a solution that is "smoother" than the brute force method I came up with. [wink] This first code is part of the program I used for isolating the problem, basically, the problem is when I enter a letter for input the program will enter into an infinite loop.
#include<iostream>
using std::cout;
using std::cin;
bool isDigit(int);
void main()
{
int inputValue;
bool inputValid;
do
{
cout<<"Enter a number between 0 - 9: ";
cin>>inputValue;
if( isDigit(inputValue) )
{
inputValid=true;
}
else
{
inputValid=false;
}
} while(isDigit);
cout<<"The number you entered is: "<<inputValue<<"\n\n";
}
bool isDigit(int value)
{
if(value>=0 && value<=9)
{
return true;
}
else
{
return false;
}
}
And I had to modify this program pretty heavily to get a work around this problem:
#include<iostream>
using std::cout;
using std::cin;
bool isDigit(int);
void main()
{
//int inputValue;
char inputValue[2];
//bool inputValid;
bool incorrect;
int firstDigit;
int secondDigit;
int finalValue;
do
{
incorrect = true;
inputValue[0] = 'z';
inputValue[1] = 'z';
cout<<"Enter a number between 0 - 99: ";
cin>>inputValue;
firstDigit = inputValue[0] - 48;
secondDigit = inputValue[1] - 48;
//cout<<inputValue[0]<<" - "<<inputValue[1]<<" - "<<finalValue;
if( isDigit(firstDigit) && isDigit(secondDigit) )
{
//inputValid=true;
finalValue = firstDigit * 10 + secondDigit;
}
else if( isDigit(firstDigit) )
{
//inputValid=false;
finalValue = firstDigit;
}
else
{
finalValue = -1;
}
//cout<<firstDigit<<" - "<<secondDigit<<" - "<<finalValue;
if(finalValue < 0 || finalValue >99)
{
incorrect = true;
cout<<"\n\nThat value is out of range. Try again. ";
}
else
{
incorrect = false;
}
} while(incorrect);
cout<<"The number you entered is: "<<finalValue<<"\n\n";
}
bool isDigit(int value)
{
if(value>=0 && value<=9)
{
return true;
}
else
{
return false;
}
}
Any help is appreciated.