Search code examples
cscanf

How to fscanf only the elements that we want?


I want to do fscanf on a .txt file, here's how it looks

7  6
[1,2]="english"
[1,4]="linear"
[2,4]="calculus"
[3,1]="pe"
[3,3]="Programming"

I want to take only the 2 numbers in the brackets, the first is day, and the second is session, and I also want to take the string subject

Here's the whole code

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(){
    FILE *inputFile, *outputFile;
    
    int day;
    int session;
    char subject[15];
    
    inputFile = fopen("Schedule.txt", "r");
        if (inputFile == NULL) {
            puts("File Schedule.txt Open Error.");
        }
    
    fscanf(inputFile, "%d %d %s", &day, &session, subject);
    
    printf("%d", day);
    
    fclose(inputFile);
    
    return 0;

}

Apparently the fscanf does not work the way i want it to.

The expected output is storing the numbers to the variables I have assigned

What actually happened is it only printed out '7'


Solution

  • to take only the 2 numbers in the brackets, the first is day, and the second is session, and I also want to take the string subject

    (I leave OP to handle first line "7 6\n".)

    Drop all fscanf() calls. Use fgets() to read a line and then parse.

    char buf[100];
    if (fgets(buf, sizeof buf, inputFile)) {
      // Parse input like <[1,2]="english"\n>
      int day;
      int session;
      char subject[15];
      int n = 0;
      sscanf(buf, " [%d ,%d ] = \"%14[^\"]\" %n",
        &day, &session, subject, &n);
      bool Success = n > 0 && buf[n] == '\0';
      ...
    

    Scan the string. If entirely successful, n will be non-zero and buf[n] will pointer to the string's end.

    " " Consume optional white spaces.
    "[" Consume a [.
    "%d" Consume optional spaces and then numeric text for an int.
    "," Consume a ,.
    "]" Consume a ].
    "\"" Consume a double quote mark.
    "%14[^\"]" Consume 1 to up to 14 non-double quote characters and form a string.
    "%n" Save the offset of the scan as an int.