Use sscanf to read multiple times string

2019-02-24 18:14发布

问题:

I'm trying to read the content of a string, inside a multidimensional array...the problem is, when I do this, the sscanf continues reading only the first character only...

On my string I have this:

A1+A2+A3+A4.

I want to read %c%d , I can read this if it was only A1, but when this case happens, it only reads A1...

I did this to read only the first character:

if(sscanf(array[line][colum], "%c%d", &colum, %line) == 2){
   printf("COL: %c, Line: %d", colum, line);

What can I do to read the entire string?

回答1:

Use the %n specifier in the format string.

E.g.

#include <stdio.h>

int main(void){
    const char *str="A1+A2+A3+A4.";
    char col;
    int line;
    int offset = 0, readCharCount;
    while(sscanf(str + offset, "%c%d%*c%n", &col, &line, &readCharCount)==2){
        printf("%c, %d\n", col, line);
        offset += readCharCount;
    }
    return 0;
}
/* result
A, 1
A, 2
A, 3
A, 4
*/