Home > Software engineering >  How to fscanf only the elements that we want?
How to fscanf only the elements that we want?

Time:11-26

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'

CodePudding user response:

An approach reading line by line and using sscanf

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

#define LINEBUFSIZE 500

int main(){
    FILE *inputFile;
    
    char line[LINEBUFSIZE];
    
    inputFile = fopen("Schedule.txt", "r");
    if (inputFile == NULL) {
        puts("File Schedule.txt Open Error.");
    }

    while (fgets(line, LINEBUFSIZE, inputFile)) {
        int day;
        int session;
        char subject[15];
        int r;
        // s because char subject[15] (14 char   null)
        r = sscanf(line, "[%d,%d]=s", &day, &session, subject);
        if (r != 3)
            // Could not read 3 elements
            continue;
        printf("%d %d %s\n", day, session, subject);
    }

    return 0;

}

CodePudding user response:

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 ] = \"[^\"]\" %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.
"[^\"]" Consume 1 to up to 14 non-double quote characters and form a string.
"%n" Save the offset of the scan as an int.

  • Related