convert string to float

J

Juhan Voolaid

Hi

I'm having hard time finding a way to convert:

std::string input="10.5";
to
float input2;

help is appreciated,
Juhan Voolaid.
 
R

Ron Natalie

Juhan said:
Hi

I'm having hard time finding a way to convert:

std::string input="10.5";
to
float input2;

There are two ways. C gives you strtod which converts between a char array
and double:
input2 = strtod(input.c_str(), NULL);

The C++ streams provide nice conversions to and from a variety of types.
The way to use strings with streams is to use a stringstream:

istringstream in(input);
input >> input2;
 
Joined
Feb 7, 2011
Messages
1
Reaction score
0
Juhan Voolaid said:
Hi

I'm having hard time finding a way to convert:

std::string input="10.5";
to
float input2;

help is appreciated,
Juhan Voolaid.

In C:

char input[] = "10.5";
double num;

num = strtod( input, NULL ); // to double
printf( "%8.3", num ); // back to string

-- pete
 
Last edited:

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,905
Latest member
Kristy_Poole

Latest Threads

Top