开发者

Regex with sscanf in c ignoring whitespace

I'm reading from an input file:

          # This is a comment

 Matrix A =
                    //NOTICE THIS LI开发者_C百科NE


# matrix A (2 diagonal line segments)

100 100

200 200

I can't figure how to extract the Matrix A from that line without the whitespace. Right now I have

sscanf(buffer,"%s%*[^\n]", word);

I tried

sscanf(buffer,"%*[ ]%s%*[^\n]", word); 

and

sscanf(buffer," %s%*[^\n]", word); 

and so many others

It just doesn't ignore the whitespace, it copies it in the word variable as well as the matrix a.


It would help if you made a little bit clearer exactly what you want read in and what you want ignored. Since it's not clear, I'm going to take a guess:

sscanf(input_line, " %[^=]", matrix_name);

That will leave the trailing whitespace though, so you'll need to trim that separately:

rtrim(matrix_name);

Where rtrim is something like (ignoring sanity/error checking for clarity):

// warning: untested code.
void rtrim(char *string) { 
    int pos;

    for (pos=strlen(string); pos >= 0 && isspace(string[pos]); --pos)
        ;
    string[pos] = '\0';
}


sscanf does not handle regular expressions.


As mentioned, sscanf doesn't have regular expressions. It takes a format specifier.

This is because C does not have regular expressions.

You either need to parse each line yourself, or use a regex library such as PCRE


It's easy:

char s1[100],s2[100],s3[100];
if( 3==sscanf(buffer,"%s%s%s",s1,s2,s3) && !strcmp(s2,"A") && !strcmp(s3,"=") )
  puts(s1);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜