Home > front end >  fgets and sscanf in C
fgets and sscanf in C

Time:05-28

I have a file I'm trying to extract the integers and characters out of.

10 20
0 0 #
1 0 |
2 0 |
3 0 |
3 1 -
3 2 -
3 3 -
3 4 >

My current code is:

while(fgets(line, sizeof(line), snakeFile) != NULL)
{
    if(sscanf(line, "%d %d", &ROW, &COL) == 2)
    {
        printf("ROW: %d, COL: %d\n", ROW, COL);
    }
    
    else
    {
        sscanf(line, "%d %d %c\n", &xPos, &yPos, &zType);
        printf("xPos: %d, yPos: %d, zType: %c\n", xPos, yPos, zType);
    }

}

However I get as the output:

ROW: 10, COL: 20
ROW: 0, COL: 0
ROW: 1, COL: 0
ROW: 2, COL: 0
ROW: 3, COL: 0
ROW: 3, COL: 1
ROW: 3, COL: 2
ROW: 3, COL: 3
ROW: 3, COL: 4

I would like it to get the first two integers and store it in ROW and COL and then the rest of the lines underneath it stored in xPos, yPos and zType respectively.

CodePudding user response:

You appear to be using the condition

if(sscanf(line, "%d %d", &ROW, &COL) == 2)

to determine whether you are currently processing the first line or not. However, this condition is unable to determine this, because that condition will be true with all lines, not just the first one. The function scanf will successfully match 2 numbers and will then ignore the rest of the line.

One thing you could do would be to change that line to

if ( sscanf(line, "%d %d %c\n", &xPos, &yPos, &zType) == 3 )

and to swap the contents of the if and the else block. This should work, because this condition will be true for all lines except the first one.

However, a simpler solution would be to not attempt to handle the first line inside the loop, but to instead handle that line outside the loop:

if( sscanf( line, "%d %d", &ROW, &COL) != 2 )
{
    fprintf( stderr, "Conversion failure!\n" );
    exit( EXIT_FAILURE );    
}

printf("ROW: %d, COL: %d\n", ROW, COL);

while ( fgets(line, sizeof(line), snakeFile) != NULL )
{
    if ( sscanf(line, "%d %d %c", &xPos, &yPos, &zType) == 3 )
    {
        printf(
            "xPos: %d, yPos: %d, zType: %c\n",
             xPos, yPos, zType
        );
    }
    else
    {
        fprintf(
            stderr,
            "Warning: Conversion failure occurred on one line! This could\n"
            "be harmless, for example it could be caused by an empty\n"
            "line at the end of the file.\n"
        );
    }
}

Note that you may have to add #include <stdlib.h> to be able to call the function exit.

  •  Tags:  
  • c c89
  • Related