informaticage

string to age

Dec 25th, 2020 (edited)
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.15 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. char toDigit(char c) {
  4.     if(c == '1') return 1;
  5.     if(c == '2') return 2;
  6.     if(c == '3') return 3;
  7.     if(c == '4') return 4;
  8.     if(c == '5') return 5;
  9.     if(c == '6') return 6;
  10.     if(c == '7') return 7;
  11.     if(c == '8') return 8;
  12.     if(c == '9') return 9;
  13.     if(c == '0') return 0;
  14.     return -1;
  15. }
  16.  
  17. int power(int n, int power) {
  18.     if (power == 0) return 1;
  19.  
  20.     int res = 1;
  21.     for(int i = 0; i < power - 1; i++)
  22.         res = res * n;
  23.  
  24.     return res;
  25. }
  26.  
  27. int parseInt(std::string s) {
  28.     using namespace std;
  29.     int num = 0;
  30.     for(int i = 0; i < s.length(); i++) {
  31.         if(toDigit(s[i]) == -1)
  32.             return -1;
  33.         num = num + toDigit(s[i]) * power(10, s.length() - i);
  34.     }
  35.     return num;
  36. }
  37.  
  38. int main ( ) {
  39.     using namespace std;
  40.     cout << "Inserire N (0, 130): " << endl;
  41.     string age;
  42.     cin >> age;
  43.  
  44.     int output = parseInt(age);
  45.     if (output == -1)
  46.         cout << "Numero non valido" << endl;
  47.     else
  48.         if(output < 0 || output > 130)
  49.             cout << "Eta fuori range" << endl;
  50.         else
  51.             cout << output << endl;
  52.  
  53.     return 0;
  54. }
  55.  
Add Comment
Please, Sign In to add comment