String to Double Function

Because MinGW C++ doesn't have the atod() or atoi() functions for some reason, I had to code a string to double function myself. I think it's working correctly, if you see any obvious pitfalls, can you mention them? Thankyou.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
double stringToDouble(std::string input) {
	bool isDecimal;
	int decimalLoc;
	double output = 0;
	double n;
	for (int i = 0; i < input.length(); i++) {
		if (input[i] == '.') {
			isDecimal = true;
			decimalLoc = i;
			break;
		}
	}
	if (isDecimal) {
		n = 1;
		for (int i = decimalLoc - 1; i != -1; i--) {
			output = output + ((input[i] - '0') * n);
			n = n * 10;
		}
		n = 10;
		for (int i = decimalLoc + 1; i < input.length(); i++) {
			output = output + ((input[i] - '0') / n);
			n = n * 10;
		}
	}
	else if (!isDecimal) {
		n = 1;
		for (int i = input.length() - 1; i != -1; i--) {
			output = output + ((input[i] - '0') * n);
			n = n * 10;
		}
	}
	return output;
}
If you don't have access to atod or atoi then it's conventional to use string streams http://www.cplusplus.com/articles/D9j2Nwbp/
1
2
3
4
5
6
7
template <typename T>
  T StringToNumber ( const string &Text )
  {
     istringstream ss(Text);
     T result;
     return ss >> result ? result : 0;
  }

Usage: StringToNumber<Type> ( String );
Topic archived. No new replies allowed.