Originally posted by Sebastiani
A file stream. For console input, the file stream is called stdin. So:
fgets(str, 100, stdin);
Or wrap it:
char *get(char str[], int max) {
return fgets(str, max, stdin);
}
Thanks, wasn't aware of that.
Anyways, here it is now (still doesn't work.. works even less actually):
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-29-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()
{
bool doAgain;
char again[100];
int ai;
int bi;
doAgain = true;
do
{
cout << "Enter a:";
ai = getNumber();
cout << endl << "Enter b:";
bi = getNumber();
cout << endl;
factor(ai,bi);
cout << "Again? (Y/N) ";
fgets(again,100,stdin);
if(again[0] == 'n' || again[0] == 'N')
{
doAgain = false;
}
else
{
doAgain = true;
}
}while(doAgain == true);
return 0;
}
int checkSize(int a)
{
if(a > 32766)
{
return 0;
}
if(a < 32766) return 1;
return 0;
}
int checkNumeric(char a[256])
{
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;
return 0;
}
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: ";
fgets(a, 256,stdin);
isNum = checkNumeric(a);
if(isNum == 1)
{
p = &a[0];
r = atoi(p);
isSize = checkSize(r);
if(isSize != 1)
{
r = getNumber();
}
else return r;
}
if(isNum == 0)
{
r = getNumber();
}
return r;
}
AHh why am I having so much trouble with something that should be so simple? (or would have been simple in C)