Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include<string>
- #include<math.h>
- using namespace std;
- int parseInt(string&);
- //turns any string that can be turned into a positive integer,
- //into a positive integer.
- //returns -1 as an error message if string contains anything but digits
- //otherwise returns the integer.
- //WORKS ONLY IN BASE-10!!!!!!!!!
- //... you heard that, you hexadecimal wankers...
- int parseInt(string& s)
- {
- //initialize the value to be returned
- int value = 0;
- int a=0;
- int b=0;
- //loop through the argument string
- for(int i=0;i<s.length();i++)
- {
- //if the character in slot i is a digit, that is a whole number
- //greater or equal to zero, and less or equal to nine
- //do following
- if(s.at(i)>='0' && s.at(i) <= '9')
- {
- //typecasting a char to an int gives the ASCII value of said char
- //since number 0 is ASCII 48, subtracting 48 from the ASCII value
- //of the character '0' ends us up with the actual integer 0.
- //same applies for 1, 2, 3 and so on.
- cout << "i=" << i << endl;
- cout << "(int)(s.at(i)-48 = " << (s.at(i)-48) << endl;
- cout << "pow(10,s.length()-(i+1) = " << (pow(10,s.length()-(i+1))) << endl;
- a=(s.at(i)-48);
- cout << "a=" << a << endl;
- b=(pow(10,s.length()-(i+1)));
- cout << "b=" << b << endl;
- value=value+a*b;
- cout << "value before modification: " << value << endl;
- value = value + /*(int)*/((s.at(i)-48))*(pow(10,s.length()-(i+1)));
- cout << "Value after modification " << value << endl;
- }
- else
- {
- return -1;
- }
- }
- return value;
- }
- int main()
- {
- string input = "";
- cin >> input;
- int value = parseInt(input);
- cout << input << endl << value;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement