My program is supposed to go through each character in a string and check if it is a number; if so it returns the number as a variable, if not, it returns "This is not a number" however the number value is returned no mater what the character is so what is wrong?
string exp;
int numValue;
int main() {
int i = 0;
cout << "Enter an expression: ";
getline(cin, exp);
for (i = 0; i < exp.length(); ++i) {
numValue = exp.at(i)-48;
if (0 <= numValue <= 9) {
cout << numValue << endl;
}
else {
cout << "This is not a number";
}
}
example input: "p133s3 f1x"
example output:
64
1
3
3
67
3
-16
54
1
72
correct output:
This is not a number
1
3
3
This is not a number
3
This is not a number
This is not a number
1
This is not a number
Your inequality statement is incorrect. 0 <= numValue <= 9 does not do what you think; rather, it will calculate one of the <=, then compare that boolean result (true or false) to the other integer. Instead, try using && to write the two inequalities separately.
0 <= numValue <= 9 is wrong.First only 0 <= numValue is analised. the result is next evaluated with <=9. 0 <= numValue is ever <=1 so the last sentence give 1<=9 that is always true. Try changing your code to (0 <= numValue)&&(numValue <= 9).