Hey all.
I just have a small question which has been bugging me for the last day or so. Consider the following program:
Now you run the program, but don't enter a number. Instead, you enter the character 'd'. Is there a reason that test now contains the value 0? I thought you could use int/char fairly interchangeably like within C. What I mean is, in C, if you tried to store 'd' in an integer, it would store the value 100, in the integer identifier (assuming the charset to be ASCII).Code:#include <iostream.h> #include <stdlib.h> int main(void) { int test; cout << "Enter a number: "; cin >> test; cout << test << endl; /* I'm aware you can use isdigit() here */ if ((test < 1) || (test > 9)) { cerr << "Invalid input.\n"; exit(EXIT_FAILURE); } /* Do some other neat program type stuff here. */ return 0; }
It might sound pointless to ask as to why it does this, but let's say the program was altered slightly, and the if statement was changed to:
If someone entered 'd' into this program, the if condition would be false, and so it wouldn't exit with the error handling code. Again, I know you could use isdigit() here, but this just seems very strange to me.Code:if ((test < 0) || (test > 5))
Haven't slept in 2 days now though, so apologies if I'm not making sense.
Thanks.
John.



LinkBack URL
About LinkBacks



