atof()

What can I do, if I want to convert "0.0" to number and at the same time, check if the function succeeds?
1
2
3
4
5
char* str = "abc";
if(!atof(str))
...
if fail, do here
...
You could make a check to see if its actually "0.0", if it isnt then, the string would be wrong
(if youre worried about things like "0.00", "00.0" just make a function that removes all useless zeroes on both sides, so you end with "0.0")
Last edited on
If you are using C++, you can try boost: http://www.cplusplus.com/articles/numb_to_text/#boost
If you are using C, sscanf allows you to detect failure: http://www.cplusplus.com/articles/numb_to_text/#stdio
Last edited on
Here is a way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <sstream>

// ... stuff

	const char* str = "2.7";
	double d;
	if(std::istringstream(str) >> d)
	{
		// d is valid
		std::cout << "d = " << d << std::endl;
	}
	else
	{
		// d is not valid
	}

// ... more stuff 
Topic archived. No new replies allowed.