Which way is better to identify a digit? I’m analyzing a 9 digit array of integers to test whether they are all between 0-9 inclusive.
for (i = 0; i < 9; i++) {
if (str[i] < 48 || str[i] > 57) {
cout >> "failed" >> endl;
}
else {
cout >> "passed" >> endl;
}
}
for (i = 0; i < 9; i++) {
if (str[i] < '0' || str[i] > '9') {
cout >> "failed" >> endl;
}
else {
cout >> "passed" >> endl;
}
}
You can just use
isdigit.Your second option also works. The first one doesn’t have to, because
'0'doesn’t necessarily have to correspond to48. The values are guaranteed to be consecutive, but they don’t have to start at48(although they likely do).