【问题标题】:Reading and storing ints with scanf in C在 C 中使用 scanf 读取和存储整数
【发布时间】:2010-12-16 11:09:06
【问题描述】:

我有一个如下所示的文本文件:

1 2 4
3 5 2
9 7 6
4 2 6

大小未知,最多 50 行。

我正在尝试将整数存储在结构数组中

typedef struct column{
int col_1;
int col_2;
int col_3;
} column;

我已经创建了 stuct 列的数组

column column[50];

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


FILE * myfile;
 int i = 0;

if ((myfile = fopen("/home/numbers.txt","r"))==NULL)
{
    printf("File %s not found\n", "/home/numbers.txt");
    exit(0);
}
if ("/home/numbers.txt" == NULL)
{
    printf("There was an error reading %s", "/home/numbers.txt");

}

while(fscanf(myfile,"%d %d %d", &column[i++].col_1, &column[i].col_2, &column[i].col_3) == 3)
{
   printf("\n%d %d %d", column[i].col_1, &column[i].col_2, &column[i].col_3);
}  

我得到一个这样的数字列表

    -420921 -420924 -420927

这似乎是一些内存地址,因为它们显然不是实际数字。

我的问题是获取整数而不是一些相当随机的数字,我在 printf 中的变量之前尝试过 &,但没有奏效,反之亦然。

非常感谢您的帮助。

【问题讨论】:

标签: c scanf


【解决方案1】:
if ("/home/numbers.txt" == NULL)

...永远不会是真的。

试着改变你的循环:

while(i < 50 && fscanf(myfile,"%d %d %d", &column[i].col_1, &column[i].col_2, &column[i].col_3) == 3)
{
   printf("\n%d %d %d", column[i].col_1, column[i].col_2, column[i].col_3);
   i++;
} 

...事实上,在确定 scanf 的参数时,您正在递增计数器,并传入 who-knows-what。

【讨论】:

  • “你在读取第一个值后递增你的计数器,而不是读取其余的正确索引。”并不真地。在调用函数之前不会读取任何内容,并且是在评估参数之后。所以不是在读取第一个值之后。但是没有指定评估的顺序,所以你是正确的,其他两个整数可能也可能不会使用不正确的索引来读取
  • 谢谢!它总是简单的事情!
【解决方案2】:

这里有很多问题 - 这个:

if ("/home/numbers.txt" == NULL)
{
    printf("There was an error reading %s", "/home/numbers.txt");

}

没有做任何明智的事情 - 摆脱它。并且您的循环代码具有未定义的行为。打印出您读取的值后,在循环体中增加您的索引。

【讨论】:

    【解决方案3】:

    这似乎是一些记忆 地址,因为它们显然是 不是实际数字。

    那是因为您正在打印地址!

    printf("\n%d %d %d", column[i].col_1, &column[i].col_2, &column[i].col_3);
    

    (除了 col_1,您/正在打印地址)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多