使用fscanf和数组

时间:2014-05-17 19:52:56

标签: c arrays file scanf

#include <stdio.h>
#include <stdlib.h>


int main()
   {

    FILE *buildingsptr;
    int ptr2[8];


    buildingsptr=fopen("buildings.txt","r");

    fscanf(buildingsptr, "%d", &ptr2);
    printf("%d", ptr2);


getch();
return 0;
}

我有一个更大的代码,我发现这部分导致了问题。 “buildings.txt”文件中有一些整数,如24或7,我只想打印第一个数字的文本,但这段代码给了我一个像2293296的数字,我是新编码,所以我不能解决我的问题,如果你帮助我,我将不胜感激。 :)

1 个答案:

答案 0 :(得分:1)

ptr2是一个数组。您想要获取(并打印)其中一个元素

fscanf(buildingsptr, "%d", &ptr2[2]); // fetch into the element with index 2
printf("%d", ptr2[2]); // print the value of the element with index 2

但是你真的应该检查fscanf()(以及之前的fopen())的返回值,以确保一切正常

if (fscanf(buildingsptr, "%d", &ptr2[2]) != 1) {
    // there was an error
} else {
    printf("%d", ptr2[2]);
}

不要忘记fclose()文件句柄。