monkeyking
February 18th, 2009, 02:56 AM
I'm quite puzzled by this small program, can someone elaborate why the following program gives different results
#include <iostream>
#include <sstream>
///convert string to double
double to_double(std::string a){///@param a is the string to convert.
double str;
std::stringstream ss;
ss<<a;
if(!(ss>>str)){
printf("Error converting :\"%s\" will exit\n",a.c_str());
exit(0);
}
ss>>str;
return str;///@return The double value.
}
///Convert string to float.
float to_float(std::string a){///@param a is the string to convert.
float str;
std::stringstream ss;
ss<<a;
if(!(ss>>str)){
printf("Error converting :\"%s\" will exit\n",a.c_str());
exit(0);
}
ss>>str;
return str;///@return The float value.
}
int main(){
std::string var = "147541611";
printf("%s <-> %f\n",var.c_str(),to_double(var));
printf("%s <-> %f\n",var.c_str(),to_float(var));
return 0;
}
output
./a.out
147541611 <-> 147541611.000000
147541611 <-> 147541616.000000
The to_float function doesn't work but a 9 digit number should still be within the limit of a float?
thanks in advance
#include <iostream>
#include <sstream>
///convert string to double
double to_double(std::string a){///@param a is the string to convert.
double str;
std::stringstream ss;
ss<<a;
if(!(ss>>str)){
printf("Error converting :\"%s\" will exit\n",a.c_str());
exit(0);
}
ss>>str;
return str;///@return The double value.
}
///Convert string to float.
float to_float(std::string a){///@param a is the string to convert.
float str;
std::stringstream ss;
ss<<a;
if(!(ss>>str)){
printf("Error converting :\"%s\" will exit\n",a.c_str());
exit(0);
}
ss>>str;
return str;///@return The float value.
}
int main(){
std::string var = "147541611";
printf("%s <-> %f\n",var.c_str(),to_double(var));
printf("%s <-> %f\n",var.c_str(),to_float(var));
return 0;
}
output
./a.out
147541611 <-> 147541611.000000
147541611 <-> 147541616.000000
The to_float function doesn't work but a 9 digit number should still be within the limit of a float?
thanks in advance