Reputation: 1
Im working on this for a week, but still cant find the solution, when I print the elements of structure person inside the function "LoadPerson" it cout it ok, but when I try it inside main, it mess. I know there must be some problem with how the elements got stored, but I have no idea what is wrong.Thank you for any help in advance
PS: the text file contains just lines in patter Name;Surname;Age
#include <iostream>
using namespace std;
struct TOsoba {
char name[20];
char surname[20];
int age;
};
void LoadPerson(FILE* file, TOsoba person)
{
char str[20];
char tempAge[5];
fgets(str, 20, file);
char *token1, *next_token1;
token1 = strtok_s(str, ";", &next_token1);
int order_in_lane = 0;
while (token1 != NULL)
{
if (order_in_lane == 0)
{
memcpy(person.name, token1, strlen(token1) + 1);
//cout << person.name << endl;
token1 = strtok_s(NULL, ";", &next_token1);
}
else if (order_in_lane == 1)
{
memcpy(person.surname, token1, strlen(token1) + 1);
//cout << person.surname << endl;
token1 = strtok_s(NULL, ";", &next_token1);
}
else if (order_in_lane == 2)
{
memcpy(tempAge, token1, strlen(token1) + 1);
person.age = atoi(tempAge);
//cout << person.age << endl;
token1 = strtok_s(NULL, ";", &next_token1);
}
order_in_lane++;
}
}
int LoadManyHuman(TOsoba osoby[], const char* jmeno_souboru)
{
FILE* file;
int pocet = 0;
fopen_s(&file, jmeno_souboru, "r");
if (file == NULL) {
perror("Error opening file");
return (-1);
}
while (!feof(file)) {
LoadPerson(file, osoby[pocet]);
pocet++;
}
fclose(file);
return (pocet);
}
void OutputHumans(TOsoba persons[], int amount)
{
// vypise osoby - prijmeni jmeno Vek
for (int i = 0; i < amount; i++)
{
cout << persons[amount].name;
cout << persons[amount].surname;
cout << persons[amount].age << endl;
}
}
int main()
{
TOsoba ManyHumans[50];
int pocet_osob = LoadManyHuman(ManyHumans, "osoby.txt");
OutputHumans(ManyHumans, pocet_osob);
}
Upvotes: 0
Views: 91
Reputation: 3219
In LoadPerson you pass a value :
void LoadPerson(FILE* file, TOsoba person)
So you can not modify its contents. You must have a pointer to a TOsoba to be able to modify it.
void LoadPerson(FILE* file, TOsoba *person)
Or by reference (thanks to @Thomas Matthews
void LoadPerson(FILE* file, TOsoba &person)
Then change other parts of code according to this.
Upvotes: 1