gpt4 book ai didi

c - 将 fscanf 与数组一起使用

转载 作者:行者123 更新时间:2023-11-30 19:19:49 25 4
gpt4 key购买 nike

#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 这样的数字,我是编码新手,所以我不能解决我的问题,如果你帮助我,我将不胜感激。 :)

最佳答案

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()文件句柄。

关于c - 将 fscanf 与数组一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23715497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com