Advertisement
Guest User

Untitled

a guest
Dec 14th, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.89 KB | None | 0 0
  1. #include<iostream>
  2. #include<string>
  3. #include<math.h>
  4. using namespace std;
  5. int parseInt(string&);
  6.  
  7. //turns any string that can be turned into a positive integer,
  8. //into a positive integer.
  9. //returns -1 as an error message if string contains anything but digits
  10. //otherwise returns the integer.
  11. //WORKS ONLY IN BASE-10!!!!!!!!!
  12. //... you heard that, you hexadecimal wankers...
  13. int parseInt(string& s)
  14. {
  15.     //initialize the value to be returned
  16.     int value = 0;
  17.     int a=0;
  18.     int b=0;
  19.     //loop through the argument string
  20.     for(int i=0;i<s.length();i++)
  21.     {
  22.         //if the character in slot i is a digit, that is a whole number
  23.         //greater or equal to zero, and less or equal to nine
  24.         //do following
  25.         if(s.at(i)>='0' && s.at(i) <= '9')
  26.         {
  27.             //typecasting a char to an int gives the ASCII value of said char
  28.             //since number 0 is ASCII 48, subtracting 48 from the ASCII value
  29.             //of the character '0' ends us up with the actual integer 0.
  30.             //same applies for 1, 2, 3 and so on.
  31.             cout << "i=" << i << endl;
  32.             cout << "(int)(s.at(i)-48 = " << (s.at(i)-48) << endl;
  33.             cout << "pow(10,s.length()-(i+1) = " << (pow(10,s.length()-(i+1))) << endl;
  34.             a=(s.at(i)-48);
  35.             cout << "a=" << a << endl;
  36.             b=(pow(10,s.length()-(i+1)));
  37.             cout << "b=" << b << endl;
  38.             value=value+a*b;
  39.             cout << "value before modification: " << value << endl;
  40.             value = value + /*(int)*/((s.at(i)-48))*(pow(10,s.length()-(i+1)));
  41.             cout << "Value after modification " << value << endl;
  42.         }
  43.         else
  44.         {
  45.             return -1;
  46.         }
  47.     }
  48.     return value;
  49. }
  50.  
  51. int main()
  52. {
  53.     string input = "";
  54.     cin >> input;
  55.     int value = parseInt(input);
  56.     cout << input << endl << value;
  57.     return 0;
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement