Convert a String to a Signed Integer
There are of course numerous functions to do this but without resorting to those here's how this can be done in C++. Note that we are assuming the input is well formatted and includes no commas or spaces. If that's not the case, it's trivial to amend this function to cater for those variations. The only real "cleverness" in this puzzle is line 14 where we subtract two characters to get an integral value of the digit.
1: #include <iostream>
2: #include <string>
3:
4: using namespace std;
5:
6: int toInt(string s)
7: {
8: int ans = 0, exp = 1;
9: for(int pos=s.length()-1; pos >= 0; --pos){
10: if (s[pos] == '-'){
11: ans = ans * -1;
12: break;
13: }
14: ans = ans + (s[pos] - '0')*exp;
15: exp = exp * 10;
16: }
17: return ans;
18: }
19:
20: int main(int argc, char* argv[])
21: {
22: cout << toInt("-678") << endl;
23: cout << toInt("21140") << endl;
24: cout << (toInt("21140") + toInt("-678")) << endl;
25: cout << toInt("0") << endl;
26: cout << toInt("") << endl;
27:
28: return 0;
29: }
26 Jun 2008 Damien Wintour 0 comments







