user5460917
user5460917

Reputation:

When reading input from a file, my program is not reading the integers correctly

I've got a text file that I am supposed to read with file input/output techniques:

47900       31007
34500        9100
57984       14822

Here is my code:

#include <stdio.h>

 FILE *input;
 int CA1;
 int CA2;
 int CA3;
 int CL1;
 int CL2;
 int CL3;


int main (void)
{
    input = fopen("c:\\class\\currentratio.txt","r");
    fscanf(input,"%d %d\n", &CA1, &CL1);
    fscanf(input, "%d %d\n", &CA2, &CL2);
    fscanf(input, "%d %d\n", &CA3, &CL3);
    printf("%d", &CA1);
    fclose(input);
    return 0;
}

When I print the numbers, they are

4229680, 4229704, 4229744, 4229712, 4229664, and 4229720.

Upvotes: 1

Views: 863

Answers (1)

ProXicT
ProXicT

Reputation: 1933

You are printing the address of the variable and not its value.
Get rid of the address: printf("%d", CA1);

Also, you are not checking whether opening the file succeeded. You should handle it, especially in case something doesn't work as expected.

if(!input)
{
    printf("Could not open the file specified.");
    return -1;
}

Upvotes: 6

Related Questions