views:

90

answers:

3

I'm trying to write a method to set 2 variables to the numbers in a char string. The string would look something like:

[-][1][ ][ ][ ][ ][2][.][0][4]

Where the numbers -1 and 2.04 could be extracted. I know the method signature could look something like this:

sscanf(array[i],"%d%f",&someint,&somedouble)

But I'm honestly not sure how to go about writing it. Any help would be greatly appreciated

+4  A: 

you're almost there :

sscanf(array[i], "%d %lf",&someint, &somedouble)

where the space means "0, 1 or more of any blank character"

but if you are using C++ and not C, better start off with the C++ streams. It will be much easier.

#include <sstream>
std::istringstream my_number_stream(array[i]);
if (!(my_number_stream >> std::skipws >> someint >> somedouble)) {
    // oh noes ! an error !
}
BatchyX
I really only just started using C++, so I'm not really familiar with streams. Is there an easy way to do this in C?
Nick
Just use the sscanf line i just wrote, with some error checking (ie : sscanf should return the number of element that it succeded to read, that is 2). Or i didn't understand your question.
BatchyX
+3  A: 

This should do your job:

    int x;
    float y;
    const char* ss = "-1    2.04";
    istringstream iss(ss);
    iss >> x >> y;
aeh
A: 

If the input is provided by user, e.g. someone has typed it, first you should normalize it: change many spaces to one, replace tabs with space, replace comma with point (some folks use comma for decimal separator instead of point), cut leading and trailing spaces, etc. Let's make sscanf()'s (or whatever you choose for parsing) job easier.

ern0
I thought sscanf was there to make *my* job easier, not the other way around ;-)
Steve Jessop