【问题标题】:Reading integer values from a file in c从c中的文件中读取整数值
【发布时间】:2014-03-03 16:36:30
【问题描述】:

我正在尝试从文件中读取数据以将他的前 n 个元素存储在数组中。数据为整数序列:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...

当我检查数组的内容时,我没有找到正确的值,似乎它正在保存正确值的地址(?)?

这是我的一段代码:

FILE* ifp;
ifp = fopen ("input.txt", "r");
int n = 10;

int* readbuf;
readbuf = (int *) malloc (n * sizeof(int));

for (int i=0; i<n; i++){
  int j = 0;
  fscanf (ifp, "%d", &j);
  j = readbuf[i];
  printf ("\n j = %d and readbuf = %d", j, readbuf[i]);
}
fclose(ifp);

如果输入文件包含以下序列,代码是否会有所不同:

0
1
2
3
...

【问题讨论】:

  • 要阅读一行你可以使用fgets。也有例子。

标签: c file scanf


【解决方案1】:

这应该可以解决它:

readbuf[i] = j;

而不是

j = readbuf[i];

【讨论】:

  • 哇,谢谢!现在我看着它,我能想到的只有 /facepalm
  • 不要让你失望。有时甚至会发生在最优秀的程序员身上。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-09
  • 1970-01-01
  • 2017-08-23
  • 1970-01-01
  • 2013-07-08
  • 1970-01-01
相关资源
最近更新 更多