Using sscanf - how to check completed scan and interrupted scan

My database provides a text file with opening and closing formulas. " set of formulas is very limited and will be easily implemented after identification. I try to use scanf to get the parameters, and I want to use the delimiter " to provide a mechanism for scanf to fail.

In the example below, the last delimiter is ignored and information that the delimiter is not found is lost. How can I control if sscanf was able to match the entire string?

 #include <stdio.h> #include <string.h> unsigned printIdentity(const char * formula){ unsigned e = 0, found = 0; double a, b; printf("-------------\n"); printf("INVESTIGATING: %s\n", formula); if( ( 2 == sscanf_s( formula, " \" X * %lf %lf \" ", &a, &b, sizeof( double ), sizeof( double ) ) ) ){ printf("MATCH: X * %lf + %lf\n", a, b); ++found; } if( ( 1 == sscanf_s( formula, " \" X * %lf \" ", &a, sizeof( double ) ) ) ){ printf("MATCH: X * %lf\n", a); ++found; } if( found != 1){ e += 1; printf("ERROR: %u formula types\n", found); } printf("-------------\n"); return e; } unsigned main( void ) { unsigned e = 0; e += printIdentity(" \"X*3.1\""); e += printIdentity(" \"X*3.2-4.2\""); e += printIdentity(" \"X*3.3+4.3\""); if( 0 != e ){ printf( "ERRORS: %2u\n", e ); } else{ printf( "all pass\n", e ); } return e; } 
+3
source share
1 answer

How can I control if sscanf was able to match the entire string?

Use the format specifier %n to get the processing completion position and compare it with the length of the input string, where the format specifier n is defined as (from section 7.19.6.2 fscanf function of the C99 standard):

Consumption is not consumed. The corresponding argument must be a pointer to a signed integer, in which the number of characters read from the input stream so far by this call to the fscanf function should be written. Execution Directive% n does not increase the account assignment returned to complete the execution of the fscanf function. No argument is converted, but one is consumed. If the conversion specification includes a character or field width assignment, the behavior is undefined.

For instance:

 #include <string.h> #include <stdlib.h> #include <stdio.h> int main() { const char* good_input = "\"20 21\""; const char* bad_input = "\"14 12"; int a[2]; int pos; if (sscanf(good_input, " \"%d %d\"%n", &a[0], &a[1], &pos) == 2 && pos == strlen(good_input)) { printf("good_input: %d %d\n", a[0], a[1]); } if (sscanf(bad_input, " \"%d %d\"%n", &a[0], &a[1], &pos) == 2 && pos == strlen(bad_input)) { printf("bad_input: %d %d\n", a[0], a[1]); } } 

Output:

  good_input: 20 21

Online demo version http://codepad.org/6G4lLXWg .

+6
source

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


All Articles