简体   繁体   English

在C中使用scanf读取和存储int

[英]Reading and storing ints with scanf in C

I have a text file that looks like this: 我有一个看起来像这样的文本文件:

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

of an unknown size upto 50 lines. 不明大小,最多50行。

I am trying to store the ints in an array of struct 我试图将int存储在struct数组中

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

I have created the array of stuct 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);
}  

I get a list of numbers like this 我得到了这样的数字列表

    -420921 -420924 -420927

It appears to be some memory addresses, because they are obviously not the actual numbers. 它似乎是一些内存地址,因为它们显然不是实际数字。

My problem is the get the ints rather than some rather random numbers, i have tried & before the variables in the printf, and that didnt work, and the other way around. 我的问题是获取整数而不是一些相当随机的数字,我已经尝试过&在printf中的变量之前,并且没有工作,反之亦然。

Your help would be greatly appreciated. 您的帮助将不胜感激。

if ("/home/numbers.txt" == NULL)

...will never be true. ......永远不会是真的。

Try changing your loop a bit: 尝试稍微改变一下循环:

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++;
} 

...as it is, you're incrementing your counter while the arguments to scanf are being determined, passing in who-knows-what. ......实际上,当你确定scanf的参数时,你正在递增你的计数器,传递谁知道什么。

Numerous things wrong here - this: 这里有很多不妥之处 - 这个:

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

}

does not do anything sensible - get rid of it. 没有做任何明智的事 - 摆脱它。 and your loop code has undefined behaviour. 并且您的循环代码具有未定义的行为。 Increment your index in the body of theloop after printing out the values you read. 打印出您读取的值后,在循环体中增加索引。

it appears to be some memory addresses, because they are obviously not the actual numbers. 它似乎是一些内存地址,因为它们显然不是实际数字。

That's because you are printing the addresses! 那是因为你正在打印地址!

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

(apart from col_1, you/re printing the address) (除了col_1,您正在打印地址)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM