Search code examples
cscanfstdio

Fscanf integers from file while ignoring surrounding characters


I'm trying to read a series of integers from a text file that is formatted as follows:

int1
int2
int3
int4
int99

ie. every integer has the same string in front of it, in this case 'int'.

I've tried the following code, but the program only prints the first integer and then ends.

FILE *fp = fopen("data.txt", "r");
int num;
while (fscanf(fp, "int%d", &num) == 1)
    printf("%d\n", num);

fclose(fp);

Solution

  • adding a space after %d will do the job.

      (fscanf(fp1,"int%d ", &num)==1)