I need to be very strict in regard to the characters that can be in a read string.
I have a series of whitespace followed by a character followed by a series of whitespace.
Examples: " c "
, "c"
, ""
, " "
I need to find a format specifier that allows me to ignore the character but only if it is this particular character and not any other character. This sequence " e "
should be aborted.
I tried " %*[c] "
but my unittests fail for some scenarios - leading me to believe that " %*[c] "
is looking for one or more 'c'
instead of zero or more 'c'
.
I wrote a mini example to help illustrate my problem better. Keep in mind that this is only a minimum example. The central issue is how do i parse an ammount of zero or one of a single character.
#include <stdio.h>
#include <string.h>
unsigned match(const char * formula){
unsigned e = 0, found = 0, s;
char del;
int parsed, pos, len = (int) strlen(formula);
const size_t soc = sizeof( char );
del = ' ';
parsed = sscanf_s( formula, " \" %*[(] X%*[^>]>> %u %*[)] %c %n", &s, &del, soc, &pos );// (X >> s )
if( ( 2 == parsed ) && ( pos == len) && ( '"' == del ) ){
printf("%6s:%s\n", "OK", formula);
}else{
printf("%6s:%s\n", "FAIL", formula);
e += 1;
}
return e;
}
unsigned main( void )
{
unsigned e = 0;
printf("SHOULD BE OK\n");
e += match(" \"X >> 3\""); //This one does not feature the optional characters
e += match(" \"( X >> 3 ) \"");
e += match(" \"( X >> 3 ) \"\r");
printf("SHOULD FAIL\n");
if ( 0 == match(" \"( Y >> 3 ) \"") ) e += 1;
if ( 0 == match(" \"g X >> 3 ) \"") ) e += 1;
if ( 0 == match(" \"( X >> 3.3-4.2 ) \"") ) e += 1;
if( 0 != e ){ printf( "ERRORS: %2u\n", e ); }
else{ printf( "all pass\n", e ); }
return e;
}
scanf
is not a general-purpose tool. I think it's impossible to implement what you want withscanf
; you can use regular expressions or manual parsing instead. – anatolyg