c - 如何将文本文件中一行中的整数分配给c中的变量?

标签 c pointers file-handling turbo-c

我有一个文本文件,其中的数字由 fprintf("%d\n",var); 提供现在文件的结构是: 1号 2号 3号 4号等 我想将数字 1 分配给 var_x,数字 2 分配给 var_y,数字 3 分配给 var_z,然后打印所有变量,然后将数字 4 分配给 var 1 等等,我该怎么做?

我尝试了 sscanf fscanf 等,但它只是打印随机数

这就是我在文件中填写数字的方式:

      fprintf(save_file,"%d\n",xaxis);
      fprintf(save_file,"%d\n",yaxis);
      fprintf(save_file,"%d\n",getpixel(xaxis,yaxis));

结果文件如下所示:

30
20
0
31
21
15
32
22
0 etc

这就是我现在正在尝试的:

sscanf(open_file,"%d",&read_x);
sscanf(open_file,"%d",&read_y);
sscanf(open_file,"%d",&read_colour);
while(!feof(open_file))
{
   printf("%d %d %d",read_x,read_y,read_colour);
   sscanf(open_file,"%d",read_x);
   sscanf(open_file,"%d",read_y);
   sscanf(open_file,"%d",read_colour);

}

预期结果是:

30 20 0
31 21 15
32 22 0

最佳答案

您可以一次扫描所有 3 个值:

#include <stdio.h>

int main() {
    FILE* f = fopen("input", "r");

    int x, y, z;

    while (fscanf(f, "%d %d %d", &x, &y, &z) > 0)
        printf("%d %d %d\n", x, y, z);
}

关于c - 如何将文本文件中一行中的整数分配给c中的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55692313/

相关文章:

c - 如何将字符串设置为全部小写

c - 使用 fscanf 时在 C 中打印 2D 字符数组时出现问题

c - 当 strtok 返回 NULL 时,strtol 给出段错误

c - unsigned char 到 8 个原始位的 unsigned char 数组

c - 如何仅计算列表中以大写字母开头的单词?

c++ - 将数字地址分配给指针

c - 为什么我们应该使用双指针在前/后添加节点,而不是在中间?

c++ - 指针数组中的值被覆盖

c# - C# 异步删除文件

swift - 如何在 Swift 中有效使用 CFSwapInt32BigToHost 、 CFSwapInt16BigToHost