user476145
user476145

Reputation: 445

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.

Upvotes: 0

Views: 1568

Answers (3)

sje397
sje397

Reputation: 41822

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.

Upvotes: 2

The Archetypal Paul
The Archetypal Paul

Reputation: 41749

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)

Upvotes: 0

unquiet mind
unquiet mind

Reputation: 1112

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.

Upvotes: 0

Related Questions