How would you convert a string, lets say:
string Numbers = "0.3 5.7 9.8 6.2 0.54 6.3";
into a float array, such as: float Numbers[6] = {0.3, 5.7, 9.8, 6.2, 0.54, 6.3};
?
Asked
Active
Viewed 1.2k times
3
-
I did some searches and seemed to be pointed to strtok, but other searches seemed to be saying you'd need a more custom function. Maybe you can find a better answer on google than I did, if someone else doesn't answer here. – TecBrat Apr 03 '12 at 01:55
-
Yea, that was my idea. I was planning on trying to use `strtok()` to break it up into the individual strings, then use `atof()` to convert the strings to floats, (bear in mind I am a novice programmer) I was having issues breaking up the string. – Sean Apr 03 '12 at 02:02
1 Answers
15
I would use data structures and algorithms from std::
:
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <cassert>
#include <sstream>
int main () {
std::string Numbers = "0.3 5.7 9.8 6.2 0.54 6.3";
// If possible, always prefer std::vector to naked array
std::vector<float> v;
// Build an istream that holds the input string
std::istringstream iss(Numbers);
// Iterate over the istream, using >> to grab floats
// and push_back to store them in the vector
std::copy(std::istream_iterator<float>(iss),
std::istream_iterator<float>(),
std::back_inserter(v));
// Put the result on standard out
std::copy(v.begin(), v.end(),
std::ostream_iterator<float>(std::cout, ", "));
std::cout << "\n";
}

Robᵩ
- 163,533
- 20
- 239
- 308
-
-
2Yes. Add `using namespace std` can introduce bugs. An OK description of the problem is here: http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-a-bad-practice-in-c – Robᵩ Apr 03 '12 at 02:15
-
2@Sean: Read the answer [here](http://stackoverflow.com/questions/1265039/using-std-namespace) with the most upvotes (I recommend never using it). – Jesse Good Apr 03 '12 at 02:17