My assignment in my extremely basic C++ class is to create a program which tells the user if a is a factor of b, and vice versa.
Well thats fine and dandy, and takes a minute to code, but as a challenge to myself I decided to make the program "smart" - not let the user crash it or enter non-numeric values. Anyways, this is what I have so far, but it just doesn't work:
The problem is that no matter what the user enters, it thinks its not a number even if it is. [edit - just made one change, fixes one problem, but still doesn't work]Code:// By Will Herrick // takes two numbers and sees if they are factors of each other. // also some practice on error-handling. // last updated 9-26-02 (doesn't work quite yet!) #include <iostream> #include <cstdlib> using namespace std; int checkSize(int); int checkNumeric(char[6]); void factor(int,int); int getNumber(); int main() { int ai; int bi; int exit = 0; int ans; do { cout << "Enter a:"; ai = getNumber(); cout << endl << "Enter b:"; bi = getNumber(); cout << endl; factor(ai,bi); cout << "Try Again(1) or Quit(2)? "; cin >> ans; if(ans == 1) exit = 0; if(ans == 0) exit = 1; else { cout << endl << "Thats not a possible choice, try again: "; cin >> ans; } } while(exit==0); system("PAUSE"); return 0; } int checkSize(int a) { if(a > 32766) { return 0; } if(a < 32766) return 1; } int checkNumeric(char a[6]) { int x; int i; int marker; for(x = 0; x < 6; x++) { i = a[x]; if((i < 48 || i > 57) && i != '\0') { marker = 1; } } if(marker == 1) return 0; if(marker != 1) return 1; } void factor(int a, int b) { if(a % b == 0) cout << b << " is a factor of " << a << endl; if(b % a == 0) cout << a << " is a factor of " << b << endl; if(a % b != 0 && b % a != 0) cout << "Neither number is a factor of the other." << endl; } int getNumber() { char a[6]; char *p; int r; int isNum; int isSize; cout << endl << "Enter the NUMBER: "; cin.get(a,6); cin.ignore(80, '\n'); isNum = checkNumeric(a); if(isNum == 1) { p = &a[0]; r = atoi(p); isSize = checkSize(r); if(isSize == 1) return r; else { r = getNumber(); return r; } } if(isNum == 0) { r = getNumber(); return r; } }
Oh and if their a much easier way of doing this that'd be great too.
Thanks.



LinkBack URL
About LinkBacks



) is that it tries to do the same error checking as yours but in a totally different way. not sure if its better or worse, but if anyone can tell me how to stop it entering the loop I'd be greatful as well