Matching trailing text in sscanf?

This is due to the use of sscanf - how to check for a completed scan and an aborted scan , but this is an edge case not covered by this question.

char entry[] = "V2X_3_accepted"; int d1,d2,ret1,ret2; ret1 = sscanf(entry,"V2X_%d_expected",&d1); ret2 = sscanf(entry,"V2X_%d_received",&d2); 

Expected Result: ret1==0; ret2==0; d1, d2 ret1==0; ret2==0; d1, d2 ret1==0; ret2==0; d1, d2 undefined.

Actual result: ret1==1; ret2==1; d1=d2=3 ret1==1; ret2==1; d1=d2=3 ret1==1; ret2==1; d1=d2=3 .

Using %n at the end will not help, since matching strings are equal in length. Is there any neat trick to match the trailing text without doing sequential strncmp or the like?

+6
source share
2 answers

Using "%n" works fine. @ user3121023

Recommend with " %n" to resolve the optional trailing space, for example << 22>, go through "V2X_3_expected\n" and check the result of %n on "V2X_3_expected 123" .

<
 char entry[] = "V2X_3_accepted"; int d1,d2; int n1 = 0; int n2 = 0; sscanf(entry,"V2X_%d_expected %n",&d1, &n1); sscanf(entry,"V2X_%d_received %n",&d2, &n2); if (n1 > 0 && entry[n1] == '\0') Success_expected(d1); else if (n2 > 0 && entry[n2] == '\0') Success_received(d2); else Fail(entry); 

Initialize n1 to a value that will never be set; the scan reached the qualifier "%n" . n1 = 0; works well in most cases, for example, in the OP format "V2X_%d_ ..." .

n1 = -1; /* and (n1 >= 0 */ n1 = -1; /* and (n1 >= 0 */ also works with short formats such as " %n" .

+2
source

The return status scanf tells you about the number of assignments that it managed to achieve if you ask one to "fill"

ret1 = sscanf(entry,"V2X_%d_expected",&d1);

and scanf succed, the return value will be 1;

So this is absolutely normal.

You can find additional documentation on using the man scanf command line.

-2
source

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


All Articles