Sscanf with multiline string

I have a line with several lines, and I want to use sscanf to match certain parts of it. However, it seems that this only works when matching the data contained in the first row.

For example, if I have a line:

"age1: x \ r \ n age2: x"

And using sscanf:

sscanf (string, "age1:% d", & i); - this works
sscanf (string, "age2:% d", & j); - However, it is not.

Any ideas?

+3
source share
5 answers

, sscanf , , , scanf fscanf. %n, , , :

int bytesRead;
if(sscanf(string, "age 1: %d\n%n", &i, &bytesRead) == 1) &&
   sscanf(string + bytesRead, "age 2: %d", &j) == 1)
{
    // success
}
else
{
    // parsing failed
}

%n : ", ( int)". , , . , %d , ; , "age 2", a , , .

+5
  • sscanf()?
  • "x" ?
  • sscanf() , "Age2:" "Age1:", .

, , , . , 2 "Age2", 1 "Age1" , . , - . .

:

#include <stdio.h>

int main(void)
{
    const char string[] = "Age1: 3\r\nAge2: 5\r\n";
    const char *scan[] = { "Age1: %d", "Age2: %d", "Age1: %d Age2: %d" };
    int age1, age2;
    int rc;

    if ((rc = sscanf(string, scan[0], &age1)) != 1)
        printf("scan failed on '%s'\n", scan[0]);
    else
        printf("scan passed on '%s' - age %d\n", scan[0], age1);

    if ((rc = sscanf(string, scan[1], &age2)) != 1)
        printf("scan failed on '%s'\n", scan[1]);
    else
        printf("scan passed on '%s' - age %d\n", scan[1], age2);

    if ((rc = sscanf(string, scan[2], &age1, &age2)) != 2)
        printf("scan failed on '%s'\n", scan[2]);
    else
        printf("scan passed on '%s' - age1 %d, age2 %d\n", scan[2], age1, age2);

    return 0;
}

scan passed on 'Age1: %d' - age 3
scan failed on 'Age2: %d'
scan passed on 'Age1: %d Age2: %d' - age1 3, age2 5
+1

sscanf , sscanf age2 age1, , .

, :

sscanf(string, "age1: %d \n\r age2: %d", &i, &j);
+1

A line has no way of remembering where sscanf was after reading the first line. (If you want this, you can look at the return value and remember it yourself.)

But you can just do it in one call:

sscanf(string, "age1: %d age2: %d", &i, &j);
0
source

if you are limited to c (i.e. you cannot use std :: getline), the easiest way is to read the data at a time and analyze it yourself.

You can use atoi and atof to convert any numbers

-1
source

Source: https://habr.com/ru/post/1775694/


All Articles