开发者

How to do conditional parsing with fscanf?

I have some lines I want to parse from a text file. Some lines start with x and continue with several y:z and others are composed completely of several y:zs, where x,y,z are numbers. I trie开发者_高级运维d following code, but it does not work. The first line also reads in the y in y:z.

...
if (fscanf(stream,"%d ",&x))
if else (fscanf(stream,"%d:%g",&y,&z))
...

Is there a way to tell scanf to only read a character if it is followed by a space?


The *scanf family of functions do not allow you to do that natively. Of course, you can workaround the problem by reading in the minimum number of elements that you know will be present per input line, validate the return value of *scanf and then proceed incrementally, one item at a time, each time checking the return value for success/failure.

if (1 == fscanf(stream, "%d", &x) && (x == 'desired_value)) {
    /* we need to read in some more : separated numbers */
    while (2 == fscanf(stream, "%d:%d", &y, &z)) { /* loop till we fail */
          printf("read: %d %d\n", y, z); 
    } /* note we do not handle the case where only one of y and z is present */
} 

Your best bet to handle this is to read in a line using fgets and then parse the line yourself using sscanf.

if (NULL != fgets(stream, line, MAX_BUF_LEN)) { /* read line */
   int nitems = tokenize(buf, tokens); /* parse */
}

...
size_t tokenize(const char *buf, char **tokens) {
    size_t idx = 0;
      while (buf[ idx ] != '\0') {
          /* parse an int */
          ...
      }
}


char line[MAXLEN];

while( fgets(line,MAXLEN,stream) )
{
  char *endptr;
  strtol(line,&endptr,10);
  if( *endptr==':' )
    printf("only y:z <%s>",line);
  else
    printf("beginning x <%s>",line);
}


I found a crude way to do, what I wanted without having to switch to fgets (which would probably be safer on the long run).

if (fscanf(stream,"%d ",&x)){...}
else if (fscanf(stream,"%d:%g",&y,&z)){...}
else if (fscanf(stream,":%g",&z)){
    y=x;
    x=0;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜