Advertisement
Spocoman

1. TryParse

Jan 29th, 2024
542
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.62 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3.  
  4. using namespace std;
  5.  
  6. bool isNumber(const string& s) {
  7.     if (s[0] != '-' && !isdigit(s[0])) {
  8.         return false;
  9.     }
  10.     for (size_t i = 1; i < s.size(); i++) {
  11.         if (!isdigit(s[i])) {
  12.             return false;
  13.         }
  14.     }
  15.     return true;
  16. }
  17.  
  18. int main()
  19. {
  20.     string n1, n2;
  21.     cin >> n1 >> n2;
  22.  
  23.     if (isNumber(n1) && isNumber(n2)) {
  24.         cout << stoi(n1) + stoi(n2) << endl;
  25.    }
  26.     else {
  27.         for (auto& n : { n1, n2 }) {
  28.             cout << (!isNumber(n) ? "[error] " : "") << n << endl;
  29.         }
  30.     }
  31.  
  32.     return 0;
  33. }
  34.  
  35.    
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement