1

So I'm using struct to create an address that looks like this:

typedef struct Address{
    char street[100];
    char city[100];
    char state[3];
    int zip;
}address;

I have a txt file that looks like this:

123 Anywhere
Spokane
WA
99223
500 Sprague Ave
Spokane
WA
99201
319F CEB
Cheney
WA
99004

When I read in the file I get a huge problem. It will read in a couple of lines correctly but most everything else is wrong. Any numbers are completely wrong.

int fillArray(address *array, FILE * fin){
int i=0, total=0;
do{
    fgets(array[i].street, 100, fin);
    fgets(array[i].city, 100, fin);
    fgets(array[i].state, 3, fin);      
    fgets(array[i].street, 100, fin);
    fscanf(fin, "%d", &array[i].zip);
    total++;
    i++;
}while(!feof(fin));

return total;
}

Obviously I'm doing something wrong but I'm not sure what I'm doing wrong. I thought that if I use fgets, it will get the line and then store it into the area that I needed it to. I had used fscanf for everything before hand and I didn't get anywhere either. It would just get the 123 and then Anywhere into the next places since it goes until the first whitespace it sees. Is there a way to use fscanf to get the entire line, or isn't that what fgets does? Is there a simpler way of doing this? Yes I know that I shouldn't use while(!feof(fin)), but our teacher is teaching that right now and that is what I'm going to be using for the time being. Thank you in advance. I have been searching around online and can't seem to get where I need to go.

1
  • What do you mean by "It will read in a couple of lines correctly but most everything else is wrong."? Can you be more specific? Commented Nov 20, 2013 at 2:26

1 Answer 1

1

The code is reading street twice. Perhaps try deleting that second one.

Unrelated tip: Instead of hard coding the length such as 100, use the sizeof operator. For example,

fgets(array[i].street, sizeof(array[i].street), fin);
Sign up to request clarification or add additional context in comments.

6 Comments

hahaha, I didn't even see that. Fixed a lot of the issues. Now when I print, the first address is fine but then everything else is messed up.
Is the array of structures initialized (either on the stack or with malloc)?
what would cause a negative number to appear in a string? Sp --1216999988okane is what is appearing when I print
Also - I think you should add a \n to the end of the fscanf string for the zip to consume the line feed.
our teacher set struct Address array[10] in the main file. I'm not sure that I can modify that though
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.