c++ - Making Conditional isdigit() -
first @ code:
#include <iostream> #include <ctype.h> using namespace std; int main() { int a,b; cout << "enter 2 digits" << endl; cin >> >> b; if (isdigit(a)) if (isdigit(b)) cout << a+b << endl; else cout << "invalid digit"; return 0; }
so type output blank space. want print if user hit non digit or alpha program should display invalid string or if user hit digit must show sum of 2 digits
since you're reading int
variables, enter has integers or input operator fail. if want read characters , check if digits, should read char
variables, , need convert them proper integer values before operating on them.
try like:
inline int to_int(const char ch) { return ch - '0'; } // ... char a, b; if (std::cin >> >> b) { if (std::isdigit(a) && std::isdigit(b)) std::cout << to_int(a) + to_int(b) << '\n'; else std::cout << "one not digit\n"; } else std::cout << "error in input\n";
if want input 2 generic integer values, you're on right track, need make sure input okay:
int a, b; if (std::cin >> >> b) std::cout << + b << '\n'; else std::cout << "error in input (most not integers in input)\n";
Comments
Post a Comment