How do you create an array of floats from a string?

I currently have a string of floats that I need to convert into an array of floats, how would I do this?

I need to convert this:
string Vertices = "0.3 0.5 0.7 0.2 0.4 0.6";

To this:
float Vertices[6] = {0.3, 0.5, 0.7, 0.2, 0.4, 0.6};

Last edited on
pointer?
Use an istringstream and the copy() algorithm with istream_iterators.

You should avoid the array and use a standard container, like vector. But, here is how to do it in either case.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <algorithm>  // copy()
#include <iostream>   // cin, cout
#include <iterator>   // istream_iterator, back_inserter
#include <sstream>    // istringstream
#include <string>
#include <vector>
using namespace std;

void using_vector()
  {
  cout << "\nUsing vector\n";

  string InputVertices = "0.3 0.5 0.7 0.2 0.4 0.6";
  vector <float> OutputVertices;

  cout << "input  = \"" << InputVertices << "\";\n";

  // conversion here:
  istringstream ss( InputVertices );
  copy(
    istream_iterator <float> ( ss ),
    istream_iterator <float> (),
    back_inserter( OutputVertices )
    );

  cout << "output = {";
  for (size_t n = 0; n < OutputVertices.size(); n++)
    cout << OutputVertices[ n ] << ",";
  cout << "\b};\n";
  }

void using_array()
  {
  cout << "\nUsing array\n";

  string InputVertices = "0.3 0.5 0.7 0.2 0.4 0.6";
  float OutputVertices[ 6 ];

  cout << "input  = \"" << InputVertices << "\";\n";

  // conversion here:
  istringstream ss( InputVertices );
  copy(
    istream_iterator <float> ( ss ),
    istream_iterator <float> (),
    OutputVertices
    );

  cout << "output = {";
  for (size_t n = 0; n < 6; n++)
    cout << OutputVertices[ n ] << ",";
  cout << "\b};\n";
  }

int main()
  {
  using_vector();
  using_array();
  return 0;
  }

Notice the similarities and differences on lines 14,37; 23,46; and 27,50.

Hope this helps.
Thank you, that worked perfectly!
Topic archived. No new replies allowed.