I've made a program which has test.txt file which contains following
24 Rohit Soni 1997
This is my code:
#include <stdio.h>
void main()
{
    FILE *f;
    int no,i;
    char *name;
    f=fopen("test.txt","r");
    fscanf(f,"%d %[^[0-9]]s %d ",&no, name, &i);
    printf("%d %s %d",no, name,i);
    fclose(f);
}
But it is not showing the correct output. Output is:
24 Rohit Soni 12804
Please tell me what to do.  Why is it not accepting an integer after taking string from fscanf using %[ format specifier.
                        
You should test the return code from
fscanf(); it would tell you 2 values are converted instead of the 3 you expected. You should always test the return code fromfscanf(), usually for the expected number of conversions and only very seldom will you test for EOF or 0.The problem is that a scan set
%[^…]is not a modifier for%s, and also the scan set stops at the first]unless that immediately follows the[for a regular scan set or[^for a negated scan set. So, your format string is looking for a sequence of 'not a digit nor an[' characters, followed by a]and ans— and it isn't finding the]andsin the input.You need:
You need to check that
fopen()worked. The error message should include the file name that you failed to open. (If you paid attention to command line arguments — usingint main(int argc, char **argv)— you would report the program name fromargv[0]in the error messages too.) You need to allocate space fornamerather than use an uninitialized pointer. The correct return type formain()isint— though Microsoft does allowvoid. Note that the input format ensures there is no buffer overflow.I've enclosed the name in
[…]in the output so you can see that the name includes the trailing space. The output I get is: