Executing conditional isdigit ()

Check out my code first:

#‎include‬ <iostream> #include <ctype.h> using namespace std; int main() { int a,b; cout << "Enter two digits" << endl; cin >> a >> b; if (isdigit(a)) if (isdigit(b)) cout << a+b << endl; else cout << "Invalid Digit"; return 0; } 

So, when we introduce something, we only display empty space. What I want to do is print, if the user didn’t type a number or the alpha program should display an invalid string or if the user hit any number, it should display the sum of two digits

+4
source share
2 answers

Since you are reading int variables, everything you enter must be an integer or the input statement will not work. If you want to read characters and check if they are numbers, you must read char variables, and then before using them you need to convert them to the corresponding integer values.

Try something like:

 inline int to_int(const char ch) { return ch - '0'; } // ... char a, b; if (std::cin >> a >> b) { if (std::isdigit(a) && std::isdigit(b)) std::cout << to_int(a) + to_int(b) << '\n'; else std::cout << "One is not a digit\n"; } else std::cout << "Error in input\n"; 

If you just want to enter two common integer values, then you are already on the right track, you just need to make sure that the input is ok:

 int a, b; if (std::cin >> a >> b) std::cout << a + b << '\n'; else std::cout << "Error in input (most likely not integers in input)\n"; 
+3
source

What you do is not at all what you want to do.

isdigit returns true if the passed value is a digit. This is true if the input, interpreted as a character, is a digit. This is NECESSARY what you want, because if we accept the traditional European language and ASCII character encoding, isdigit will be true if the value in a or b is in the range 48..57.

What I suppose I want to do is check if a and b valid integer values. In this case:

  if (cin >> a >> b) { cout << a + b << endl; } else { cout << "Invalid digit" << endl; } 

will be correct.

+1
source

Source: https://habr.com/ru/post/1495911/


All Articles