string to float conversion problem???

Hi All,

I have string which has more float values.i need to grap the float values from the string.i have tried like this...

#include <iostream>
int main()
{
char *str = "-16.4118804932,11.3191652298,-2.78425216675,-21.5407752991";
float f1,f2,f3,f4;
sscanf(str,"%f,%f,%f,%f,%f",&f1,&f2,&f3,&f4);
std::cout<<"f1="<<f1<<"\t"<<"f2="<<f2<<"\t"<<"f3="<<f3<<"\t"<<"f4="<<f4;
return 0;
}

here my probelm is string is constant (i.e it may have 4 or 6 or 10 values)
so in that case how shall i read the float values if the string is constant?

I want to write the generic code which should grap any number of float values in the string..Please let me know the idea in C or C++

Thanks in Advance
Senthil kumar
Last edited on
Why does your code not work?

If the string can have only 4, 6, or 10 values comma-separated, then attempt to read the maximum (10) number of floats. Remember that sscanf() returns the number of arguments actually filled in.

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <cstdio>

using namespace std;

int main() {
    const char* str = "1 2 3";
    int i1, i2, i3, i4, i5;
    cout << "The source string contains "
            << sscanf( str, "%d %d %d %d %d, &i1, &i2, &i3, &i4, &i5 )
            << " integers" << endl;
} 

Topic archived. No new replies allowed.