JWH
JWH

Reputation: 23

sscanf returns 1 despite the line not matching the search pattern

I need to read certain parameters from a file. My problem is to scan the lines of the file to find the parameters. The text file is structured in lines like:

character *\n

So each line has to have the pattern (space or tab)character[space or tab][char][space or tab]\n.

Spaces or tabs at the beginning are optional. I tried to do it with

char val;
if(sscanf(buf, "%*[ \t]character%*[ \t]%c%*[ \t]\n",&val)==1||sscanf(buf, "character%*[ \t]%c%*[ \t]\n",&val)==1){
    printf("%c in %i\n", val,line);
}else{
    fprintf(stderr,"Error while reading line %i\n",line);
}

buf contains the current line.

My problem is, in lines like character \n my program does not print an error. Instead it saves '\n' in val. I do not understand this behavior, because this line does not match my search pattern.

What is wrong with my code?

My understanding of my

Upvotes: 1

Views: 287

Answers (1)

user743382
user743382

Reputation:

I do not understand this behavior, because this line does not match my search pattern.

The *scanf functions do not check the pattern first and then, if it matches, fill in the values. They check one character at a time, and indicate how many of the fields in the format string they were able to use.

Unfortunately, in your case, %c can certainly match '\n'. The subsequent %*[ \t] fails, as would the subsequent \n, but since those aren't stored anywhere, they don't affect sscanf's return value, so you can't tell from the result whether there was any error.

The simplest way to solve this might be to not use *scanf functions at all. Your input format is easily described using a custom routine, but not so easily with a format string.

Upvotes: 1

Related Questions