simple question methinks, but its perplexing me neverthe less:
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-27-02 (doesn't work quite yet!)
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
int checkSize(int);
int checkNumeric(char[256]);
void factor(int,int);
int getNumber();
int main()
{
int ai;
int bi;
int exit;
char quit;
exit = 0;
while(exit == 0)
{
cout << "Enter a:";
ai = getNumber();
cout << endl << "Enter b:";
bi = getNumber();
cout << endl;
factor(ai,bi);
cout << "Again? (Y/N) ";
cin >> quit;
if(quit == 'y' || quit == 'Y')
{
exit = 0;
}
else exit = 1;
}
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;
int length;
length = strlen(a);
for(x = 0; x < length; 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[256];
char *p;
int r;
int isNum;
int isSize;
cout << endl << "Enter the NUMBER: ";
cin.get(a,256);
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;
}
}
The problem lie in the program loop. If the user presses y or Y to do it "again" it just does this:
Code:
Enter a:
Enter the NUMBER:
Enter b:
Enter the NUMBER:
Press Enter to continue!
without even taking anymore user input.
Also, if I use "cin.get(quit); cin.ignore(80,'\0');", the if(quit == 'y' || quit == 'Y') statement doesn't work.
Any tips?