How to use sscanf in loops?

后端 未结 1 1291
深忆病人
深忆病人 2020-11-22 00:32

Is there a good way to loop over a string with sscanf?

Let\'s say I have a string that looks like this:

char line[] = \"100 185 400 11 1         


        
相关标签:
1条回答
  • Look up the %n conversion specifier for sscanf() and family. It gives you the information you need.

    #include <stdio.h>
    
    int main(void)
    {
        char line[] = "100 185 400 11 1000";
        char *data = line;
        int offset;
        int n;
        int sum = 0;
    
        while (sscanf(data, " %d%n", &n, &offset) == 1)
        {
            sum += n;
            data += offset;
            printf("read: %5d; sum = %5d; offset = %5d\n", n, sum, offset);
        }
    
        printf("sum = %d\n", sum);
        return 0;
    }
    

    Changed 'line' to 'data' because you can't increment the name of an array.

    0 讨论(0)
提交回复
热议问题