tags:

views:

61

answers:

3

Hi there,

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 tried 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?

+3  A: 

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 */
          ...
      }
}
dirkgently
+1  A: 
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);
}
A: 

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;
}
Framester
do you mean `else if`?
Matt Joiner
yes, I corrected it.
Framester