I am having a lot of trouble extracting values from a string into a double array.
I have a string that looks something like this:
"asdf 1.320 1 234.43 5.00000 3"
All I want to do is extract the doubles and store them in an array of doubles.
Any tips?
Last edited on
Thanks, that does work for the specific string I provided.
I was wondering how to write a code that satisfies ANY case for any string with a random amount of numbers in it?
How about this?
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
|
#include <iostream>
#include <string>
#include <vector>
int main ( )
{
std::string str = "asdf 1.320 1 234.43 5.00000 3", temp;
std::vector<double> vec;
size_t i = 0, start = 0, end;
do {
end = str.find_first_of ( ' ', start );
temp = str.substr( start, end );
if ( isdigit ( temp[0] ) )
{
vec.push_back ( atof ( temp.c_str ( ) ) );
++i;
}
start = end + 1;
} while ( start );
for ( i = 0; i < vec.size ( ); ++i )
std::cout << vec[i] << '\n';
}
|
Edit: I decided to use a vector instead of an array.
Last edited on
That was very helpful, thankyou
Wow that was exactly what I needed, thanks.
Out of curiosity, how the heck do you guys just write these codes in like 3 minutes?