【问题标题】:Use of fscanf with array将 fscanf 与数组一起使用
【发布时间】:2014-05-17 19:52:56
【问题描述】:
#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 这样的数字,我是编码新手,所以我不能解决我的问题,如果你能帮助我,我将不胜感激。 :)

【问题讨论】:

    标签: c arrays file scanf


    【解决方案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()文件句柄。

    【讨论】:

    • 非常感谢,我解决了。但是如果您有时间回答我还有一个问题,我将使用 malloc 而不是数组,我从 .txt 文件中获取这些整数,我将这些数字发送到由 malloc 实现的指针,然后我想访问由 malloc 分配的那部分内存。我记得我可以使用具有内存部分的头地址的指针作为数组。例如,ptr2=(int*)malloc(a*sizeof(int));然后fscanf(buildingsptr, "%d", ptr2);如何将我的号码打印到屏幕上?我尝试了类似 ptr[i] 的“for”循环,但失败了。
    • printf("%d\n", *ptr2);打印
    • @user3648312 从不投射 malloc 开始:ptr2 = malloc(a * sizeof *ptr2); 演员阵容从 30 年前开始就很粗糙,从那时起人们就一直在复制粘贴而无需动脑筋。此外,您访问此数组的方式与另一个数组相同:ptr2[n] 以访问从0 索引的n-th 元素。
    猜你喜欢
    • 2011-10-11
    • 1970-01-01
    • 2018-08-17
    • 2017-03-19
    • 2015-10-05
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多