Hello, I'd like to write a function that checks to see if a number is a digit or not. This is as far as I've gotten, and the program just won't seem to run
I have a few questions for you.
Where in your isDigit(int) function are you checking to see if x is a digit? And you're calling the function recursively, and it will loop infinitely.
Why is isDigit(int) returning a char? Wouldn't it make more sense for it to return a boolean value?
In main, you make no reference to the function you created.
Also, in ctype.h, there is already a function called isdigit(int) that returns 0 if the digit isn't an int.
1 2
if(isdigit(x))
cout << "x is a digit." << endl;
There's no real need to make your own isDigit function.
EDIT:
I find Stewbond's description much more helpful than mine, lol.
char isDigit(char x)
{
if (isDigit(x)) // <---- You're calling your own function again.
return 1;
elsereturn 0;
You're calling your own function recursively, which results in an indefinite loop that you'll never get out of.
I think what you mean to use is the function isdigit(x) (that's defined in ctype.h.)
Bear in mind that C++ is case sensitive.
isdigit(x) is not the same thing as isDigit(x).
Ok, I tried this - I'm trying to return 1 and 0 for true/false in the function, to go to main. But the program doesn't cout 1 or 0 at the end. Just trying to make sure it works, then I'll set up something like 'if 1 do this, else do that'.
You are using a return type of char. If you want the printable characters 1 and 0, then put them in single quotes, like any other character constant.
Alternatively, return a boolean (much like my example). The default when using cout with a bool type is to print '1' or '0'. So that might be cleaner and more appropriate, since you really want a true/false outcome, (just two possibilities) while a char type allows for 256 different possibilities.