简体   繁体   中英

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);

It is because you are not consuming the new line character and it is left out in the input stream.

Just change your fscanf as below.

fscanf(fp, "int%d\n", &num) == 1
                 ^^-->read new line

在%d之后添加空格将完成此工作。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM