Pages: [1]   Go Down
Author Topic: Converting string to numeric  (Read 5992 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 5
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

In my program I need to convert a String variable to numeric float variable.

For example:
String Weight="1234.56";
float WVal=atof(Weight);

I'm getting error:  cannot convert 'String' to 'const char*' for argument '1' to 'double atof(const char*)'

Why is that error? is there a different way to convert a sting to numeric?
I would appreciate any help

Thanks


« Last Edit: January 16, 2011, 10:26:13 pm by jgubits » Logged

Colorado
Offline Offline
Full Member
***
Karma: 2
Posts: 220
Arduino 0022 and Ubuntu 11.10 64bit.
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

The simplified answer:
a) the String library is a class (object).   A class can contain member variables, constants, member functions, and overloaded operators. Its a c++ thing
b) atof expect an argument of type const char * str
c) to convert the string class to a const char * str

Code:
char buf[Weight.length()];
Weight.toCharArray(buf,Weight.length());
float WVal=atof(buf);

« Last Edit: January 17, 2011, 12:53:49 am by mrtaylor » Logged

Colorado
Offline Offline
Full Member
***
Karma: 2
Posts: 220
Arduino 0022 and Ubuntu 11.10 64bit.
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Just as a side note, I dislike converting to different types. It can inject errors and drive you crazy debugging.  I find it better in the long run to redesign the code to use the type I need, if possible.
Logged

Pages: [1]   Go Up
Jump to: