如何将文件中的数字字符串作为单独的整数存储在 C 中的数组中

How to store a number string in a file as a seperate integer in an array in C

我在 Sender.txt 中有一个 32 位的文本文件,例如

00100100101110001111111100000001

我想将每个单独的数字作为整数存储在数组中。我试过以下代码但没有用。

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

void main()
{
  FILE *myfile;
  myfile = fopen("Sender.txt" , "r");
  char data[32];
  int i,con, data1[32];

  for(i=0;i<32;i++)
  {
    fscanf(myfile, "%1s", &data[i]);
  }

  for(i=0;i<32;i++)
  {
    con = atoi(data[i]);
    data1[i]=con;   
  }

  for(i=0;i<32;i++)
  {
    printf("%d \n", &data1[i]);
  }
}

你为什么不使用 fgetc?此函数只读取一个字符并 returns 它。 你的代码应该是这样的:
这个有错误见编辑

FILE *file;
char c[32];
for(int i = 0; i < 32; i++){
    if((c[i] = fgetc(file)) == NULL)
        //then Error
}
fclose(file);

编辑: 正如 "alk" 正确指出的那样(多好的名字 xD) if 子句根本没有意义。这是一大早我道歉。正确的代码当然应该是这样的:

FILE *file;
int data[32];    //The Question was to store the Data in an int not char like i did...
for(int i = 0; i < 32; i++)      
    data[i] = fgetc(file) - '0';
fclose(file);

此致

仍然没有完全理解你努力的目的,我建议重写前两个循环:

for(i = 0; i < 32; i++)
{
    int next = fgetc(myfile);
    data1[i] = (next == '0') : 0 ? 1;   
}

此代码假定文件有 32 个 1 或 0,全部在同一行,没有其他内容。

可以进一步压缩,但可能会牺牲清晰度:

for(i = 0; i < 32; i++)
{
    data1[i] = fgetc(myfile) - '0';   
}