mardi 31 mars 2015

C++ semantic error in structure variable

I am new to programming. I was trying to parse an input which contains the records of some people in a file in the following form:


5 dave laura owen vick amr dave 200 3 laura owen vick owen 500 1 dave amr 150 2 vick owen laura 0 2 amr vick vick 0 0


The first interger that is 5 represents the total number of persons involved, after which we get 5 strings upto amr. The next input involves a string "dave" and 2 integers 200 and 3 where 3 denotes the number of persons associated with "dave". The next 3 strings are the names of the person associated with "dave". Subsequent entires represent the same semantic structure.


I coded a "structure dict" to hold the above information, and stored the names of the persons in the struct variable 'name'. However as I retrieve the data from the file into the struct variables, my code automatically changes the information in the struct variables. I am unable to locate the error and would be very thankful if any of you could help me figure my mistake. Thanks in advance.



#include "iostream"
#include "fstream"
using namespace std;

typedef struct $
{
char name[14];
int dollars;
int no_Persons;
char friends[][14];
}dict;

int main()
{
ofstream fout ("gift1.out");
fstream fin ("gift1.in");
int num;
fin >> num;
dict NP[num];
int counter = num;
char name[14];
int index;
for(int i = 0; i < counter; i ++)
fin >> NP[i].name;
while(counter)
{
fin >> name;
for(int i = 0; i < num; i++)
{
if(strcmp(name, NP[i].name)==0)
{
index = i;
break;
}
}
fin >> NP[index].dollars;
fin >> NP[index].no_Persons;
for(int i = 0; i < NP[index].no_Persons; i ++)
fin >> NP[index].friends[i];

counter --;
}

for(int i = 0; i < num; i++)
{
cout << NP[i].name << endl;
cout << NP[i].dollars << " " << NP[i].no_Persons << endl;
for(int j = 0; j < NP[i].no_Persons; j++ )
cout << NP[i].friends[j] << endl;
}
}

Aucun commentaire:

Enregistrer un commentaire