> On Fri, 21 Oct 2005 18:40:08 +0000, Marcus Kwok wrote:
You should not use the ato*() functions (atoi, atof, etc.) because you
have no way of determining whether the input was a 0 or something that
caused an error. You should prefer either the strto* functions, or
stringstreams. I like stringstreams:
#include <iostream>
#include <string>
#include <sstream>
int main()
{
std::string s = "15.4";
double d;
std::istringstream iss(s);
iss >> d;
std::cout << "value of d = " << d << '\n';
return 0;
}
Jay Nabonne <ja*********@sonicnospam.com> wrote: Since you were talking about being able to distinguish an error case from
a value of 0, would you check the state of iss after the ">>" in order to
check for that error state? I assume it would leave "d" unchanged in the
event of error?
Right, sorry, I was in a bit of a hurry when I wrote it. You could do
something like:
if (iss >> d) {
// conversion was successful
}
This program seems to indicate that if the conversion failed, then the
value of 'd' is unchanged:
#include <iostream>
#include <string>
#include <sstream>
int main()
{
std::string s = "hello";
double d = 33.0;
std::istringstream iss(s);
if (iss >> d) {
std::cout << "value of d = " << d << '\n';
}
else {
std::cout << "error converting d (d = " << d << ")\n";
}
return 0;
}
--
Marcus Kwok