user2775084
user2775084

Reputation: 105

Convert a string with various float numbers into floats.

I have a series of strings like this "50 50 10"

Each number is supposed to represent the x, y, and z values of an origin. I want to convert each number of this string into an actual float.

I tried using atof, but that gave me back just the first number, 50 in this case.

Any ideas?

Thank you!

Upvotes: 1

Views: 115

Answers (2)

Dylan Lawrence
Dylan Lawrence

Reputation: 1533

The best way to do this would be to use the string stream. This site: has a great tutorial for it. It will also allow for direct casting from string to whatever type you need. (In this case float.)

Upvotes: 0

CS Pei
CS Pei

Reputation: 11047

Use a istringstream,

int main() {

    string s = "50 50 50";

    istringstream instream;
    instream.str(s);

    double a, b, c;
    instream >> a >> b >> c;
    return 0;
}

Upvotes: 3

Related Questions