Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

unable to set values in a struct print them and copy the struct

Status
Not open for further replies.

adev111

Programmer
Jul 8, 2004
44
0
0
CA
Hello everyone,

I am trying to store data in a struct. However it doens't set the values.

I read from a text file the values below and I've also included my code for your review. I've removed the pointers from my structure.

Code:
=====
NET09   1  --
NET10   1  --
=====
#include <stdio.h>
#include <stdlib.h>


void main()   
{

int loop = 0;
typedef struct {           
     char netID[7];
        int hopCount;                     
        char nextHop[2];                     
        }Routers;

FILE *fp;
FILE *fp1;
char arr[50];
Routers router1[5];
Routers router2[5];

fp = fopen("tblE.txt","r+");

for(loop=0;loop<5;loop++)
{
fscanf(fp,"%s\t%d\t%s\n",&(router1[loop].netID)[loop],&(router1[loop].hopCount),&(router1[loop].nextHop)[loop]);
}
fclose(fp);

loop=0;
for(loop=0;loop<5;loop++)
{
printf("%s\t%d\t%s\n", router1[loop].netID,router1[loop].hopCount,router1[loop].nextHop);
} 

/* memcpy(&router1,&router2,sizeof(ROUTERS));
*/
router2=router1;
loop=0;
for(loop=0;loop<5;loop++)
{
printf("%s\t%d\t%s\n", router2[loop].netID,router2[loop].hopCount,router2[loop].nextHop);
} 
fp1=fopen("test.Txt","w");
loop=0;
for(loop=0;loop<5;loop++)
{
fprintf(fp1,"%s\t%d\t%s\n", router2[loop].netID,router2[loop].hopCount,router2[loop].nextHop));
}
close(fp1);
Would some one please advise. It's really urgent!!

Thanks
 
Hi,

This line doesn't seem correct...
Code:
[red]

fscanf(fp,"%s\t%d\t%s\n",&(router1[loop].netID)[loop],&(router1[loop].hopCount),&(router1[loop].nextHop)[loop]);
[/red]

Try this..
Code:
[blue]
fscanf(fp,"%s\t%d\t%s\n",&router1.netID,&router1.hopCount,&router1.nextHop);
[/blue]

The first and last parameters appear to be strings, so you don't need to reference the index when loading values in. That is assuming your data are words and not characters.
Secondly, hopCount does not need an index, it is an int value.

Hope that works,
-Ron

typedef map<GiantX,gold, less<std::shortestpathtogold> > AwesomeMap;
 
ronnyjljr said:
Code:
fscanf(fp,"%s\t%d\t%s\n",&router1.netID,&router1.hopCount,&router1.nextHop);
Actually, router1 is an array of Routers, so the index is required. I don't think you need the & infront of the char* types though (i.e. netID and nextHop).

Also, are you sure fscanf() is actually reading anything? Maybe it's at EOF?

You should be careful when using fscanf() to read strings, since you could easily overflow your char array.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top