string to float

hello,

how to extract individual float values from a string.
I want to accept as

string str;
cout<<"enter numbers";
getline(cin,str);

using atof I want to split the values.
how to do it.
You do it by not using atof.

1
2
3
istringstream is (str);
double MyFloat;
is >> MyFloat;


Or even simpler:
istringstream(str) >> MyFloat;
> how to extract individual float values from a string.
> I want to split the values. how to do it.

1
2
3
4
5
6
7
8
9
10
11
12
13
std::string line ;
std::getline( std::cin, line ) ;

std::vector<float> values ;

// to extract float values from the line, iterate over each white-space
// delimited sequence of chars in the line, and convert it to a float
{
    std::istringstream stm(line) ;
    float f ;
    // read each float one by one till the end (or there is an error in input)
    while( stm >> f ) values.push_back(f) ; // and add it to the sequence of float.
}


Or if you are familiar with iterators:
1
2
3
std::istringstream stm(line) ;
std::istream_iterator<float> begin(stm), end ;
std::vector<float> values( begin, end ) ;


Topic archived. No new replies allowed.