slam_duncan
slam_duncan

Reputation: 3668

C++: get individual float values from a string line of floats

Suppose we have a string line:

14.6527 39.5652 -344.226 -3.34672

Let's call this string, str_line.

My question is, how can we parse this into a float array, float data[4].

I tried using getline from stringstream but to no avail (see below for representation of my code). Any help would be appreciated :)

for(int i=0;i<4;i++){
  stringstream ss(str_line);
  ss.getline( str_line, 8, ' ' );
  data[i]=atof(ss);
}

Upvotes: 2

Views: 8903

Answers (2)

ciamej
ciamej

Reputation: 7068

You should declare stringstream object ss once, don't do it in a loop.

Then you have to only use the operator >> to extract floats from the stream.

stringstream ss(str_line);
for(int i=0;i<4;i++){
  ss >> data[i];
}

If you're reading from a file, you can use a file stream like ifstream and read floats directly from it. The stream will ignore any whitespaces including newlines.

Upvotes: 7

yizzlez
yizzlez

Reputation: 8805

Use the >> operator on stringstream:

ss >> data[i];

Upvotes: 1

Related Questions