开发者

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.

I am trying to store the ints in an array of struct

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

I have created the array of stuct column

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.

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.


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜