Trouble with scanf command in c ( cant find anywhere else in forums)

FILE *datapad;
char filename[20];
printf("please enter file \n");
scanf(" %s", &filename);
fflush(stdin);
printf("processing");
datapad = fopen(filename,"r");

So this above is code for a project I'm working on but when I compile the code and run it gets stuck at the scan f command and I can't figure out what is going wrong, I've tried the fflush command and I have the formatting right with the ampersand.

2 answers

  • answered 2018-02-13 00:39 Stephen Docy

    The format for your scanf() is incorrect

    main()
    {
        char filename[20];
        printf("please enter file \n");
        scanf("%19s", filename);
        printf("processing %s...\n", filename);
    }
    

    output:

    please enter file
    /we/sd/xc
    processing /we/sd/xc...
    

  • answered 2018-02-13 00:39 Paresh Dhandhukiya

    you have filename as array of character , here you are passing incorrent filename with scanf function. you can pass array as an arguments in two ways :

    1 ) filename : pass name of array as argument, it will point to first element of an array

    2 ) &filename[i] : pass i'th element of an array, this is helpful in the cases you have to pass element other than first element as an argument:

    following is the correct program :

    FILE *datapad;
    char filename[20];
    printf("please enter file \n");
    scanf(" %s",filename);
    fflush(stdin);
    printf("processing");
    datapad = fopen(filename,"r");