Advertisement
Rafpast

Convert a string to a number

Dec 6th, 2020
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.06 KB | None | 0 0
  1. int data()
  2. {
  3.     //A function for calculating numbers of the int type.
  4.     int x = 0, k = 0;
  5.     string text = "ddddd", help;
  6.     getline(cin, help);
  7.     text.insert(0, help);
  8.  
  9.     for (int i = 0; i < (text.size() - 5); i++)
  10.     {
  11.         if ((47 > text[i]) || (text[i] > 58))
  12.         {
  13.             k += (int)text[i];
  14.             x = k + x;
  15.         }
  16.  
  17.         else if (((47 < text[i + 5]) && (text[i + 5] < 58)) && ((47 < text[i + 4]) && (text[i + 4] < 58)) && ((47 < text[i + 3]) && (text[i + 3] < 58)) && ((47 < text[i + 2]) && (text[i + 2] < 58)) && ((47 < text[i + 1]) && (text[i + 1] < 58)) && ((47 < text[i]) && (text[i] < 58)))
  18.         {
  19.             x = (text[i] - 48) * 100000 + (text[i + 1] - 48) * 10000 + (text[i + 2] - 48) * 1000 + (text[i + 3] - 48) * 100 + (text[i + 4] - 48) * 10 + (text[i + 5] - 48) + x;
  20.             i += 5;
  21.         }
  22.  
  23.         else if (((47 < text[i + 4]) && (text[i + 4] < 58)) && ((47 < text[i + 3]) && (text[i + 3] < 58)) && ((47 < text[i + 2]) && (text[i + 2] < 58)) && ((47 < text[i + 1]) && (text[i + 1] < 58)) && ((47 < text[i]) && (text[i] < 58)))
  24.         {
  25.             x = (text[i] - 48) * 10000 + (text[i + 1] - 48) * 1000 + (text[i + 2] - 48) * 100 + (text[i + 3] - 48) * 10 + (text[i + 4] - 48) + x;
  26.             i += 4;
  27.         }
  28.  
  29.         else if (((47 < text[i + 3]) && (text[i + 3] < 58)) && ((47 < text[i + 2]) && (text[i + 2] < 58)) && ((47 < text[i + 1]) && (text[i + 1] < 58)) && ((47 < text[i]) && (text[i] < 58)))
  30.         {
  31.             x = (text[i] - 48) * 1000 + (text[i + 1] - 48) * 100 + (text[i + 2] - 48) * 10 + (text[i + 3] - 48) + x;
  32.             i += 3;
  33.         }
  34.  
  35.         else if (((47 < text[i + 2]) && (text[i + 2] < 58)) && ((47 < text[i + 1]) && (text[i + 1] < 58)) && ((47 < text[i]) && (text[i] < 58)))
  36.         {
  37.             x = (text[i] - 48) * 100 + (text[i + 1] - 48) * 10 + (text[i + 2] - 48) + x;
  38.             i += 2;
  39.         }
  40.  
  41.         else if (((47 < text[i + 1]) && (text[i + 1] < 58)) && ((47 < text[i]) && (text[i] < 58)))
  42.         {
  43.             x = (text[i] - 48) * 10 + (text[i + 1] - 48) + x;
  44.             i++;
  45.         }
  46.  
  47.         else if ((47 < text[i]) && (text[i] < 58))
  48.         {
  49.             x = (text[i] - 48) + x;
  50.         }
  51.     }
  52.  
  53.     while (x < 0)
  54.     {
  55.         cout << "Invalid value provided, please re-enter";
  56.         x = data();
  57.     }
  58.  
  59.     return x;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement