开发者

C++: sscanf behavior

Can someone help me understand this piece of code:

    char *line = new char[2048];
    char *probableCauseStr = new char[512];
    char *additioanl_text = new char[512];
    long holdPeriod = 0;

    while( !f.eof() ) {
            f.getline( line, 2048 );
            //
            // find the ',' seperator
            //
            char* p = StrMgt::strchr( line, ',' );
            if( !p ) continue;
            *p = '\0';
            p++;
            if( sscanf( line, "%s%s", probableCauseStr, additioanl_text ) != 1 || 
                sscanf( p, "%ld%s", &holdPeriod, additioanl_text ) != 1 ) continue;

            ....

I'm los开发者_如何学运维t trying to figure out what happens with the character pointer p.


p is used to find the first comma and replace it with \0 (which is the end-of-string for C-style strings, in particular for sscanf). Then p is incremented to point at the next character.

So a string like

"Hello world, 100000"

becomes

line -> "Hello world"
p -> " 100000"

Then the two sscanfs are tried, checking for whichever one returns 1 (which means that it parsed exactly 1 value). In this example, the first sscanf would return 2 (since there are two words), so the second one will be called, and will return 1, with holdPeriod getting the value 100000.


The char pointer p incremented to next char, then it the second sscanf reads data from a memory location the incremented pointer points to.

From the code, I can say the reason why p is incremented because initially the first char of p is assigned with \0. So it's incremented to the next char, to make it point to an integral value, so that sscanf can read it with %ld specifier. After this, sscanf reads a string with %s specifier.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜