写了一段代码,“123.456”倒是可以,长点的数据貌似就不行啦:
#include <iostream> #include <string> int my_power(int n) { int temp = 1; while (n--) temp *= 10; return temp; } float string_to_float(std::string s) { int n = s.size(); int i = 0; float temp1 = 0.0f,temp2=0.0f; while (i < n && s[i] != '.') { temp1 = (s[i]-'0')+temp1*10; ++i; } int j = ++i; while (j < n) { temp2 = (s[j]-'0')+temp2*10; ++j; } return temp1+temp2/my_power(n-i); } int main() { std::string s = "123.456"; std::cout << string_to_float(s) << std::endl; }