开发者

Pull out 2 numbers from a char string?

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 sig开发者_开发百科nature 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


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 !
}


This should do your job:

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜