Search code examples
cscanfstdio

How to properly use sscanf in this context?


I have a file which structure is the following:

var1 2921
var2 0.5
var3 12

I need a method that gets the name of the file and 3 empty variables. It should read the file and give a value for each variable. (This is what I have tried so far)

void get_input(char * filename, int * var1, double * var2, int * var3){
    FILE *file;
    char buf[1024];
    file=fopen(filename,"r");
    if(file == NULL){
        printf("ERROR");
        exit(0);
    }

    int i=0;

    if(file){
        while(fgets(buf,sizeof(buf),file)!=NULL){    
            switch(i){
            case 0:
                sscanf(buf,"var1 %d",&var1);
                break;
            case 1:
                sscanf(buf,"var2 %f",&var2);
                break;
            case 2:
                sscanf(buf,"var3 %d",&var3);
                break;
            default:
                break;
            }
            
            i++;
        }
    }
}

And the main:

int main()
{
    char filename[256];
    int var1,var3;
    double var2;

    snprintf(filename,256,"file.txt");

    get_input(filename,&var1,&var2,&var3);

    printf("%s %d","var1: ",var1);
    printf("%s %f","\nvar2: ",var2);
    printf("%s %d","\nvar3: ",var3);

    return 0;
}

Output:

var1: 8

var2: 0.000000

var3: 2011837489


Solution

    1. For a double, you need to use %lf, not %f; in scanf as well as in printf. Alternatively, you could use float, that goes with %f.

    2. You are passing the addresses of var1, 2, 3; so taking the address again in scanf is duplicate - you will get the address of the address.
      Use var1 instead of &var1 inside the scanf.