0

I have a file.txt that contains:

Marco Beno
Polo
15
Mario
Pollo Pollo
20

and struct defined as that:

struct person{
char name[15];
char surname[15];
int age;
}

now I want to read into this struct this file line by line, so marco beno is assigned to person.name,Polo to person.surname and so on... I have been looking for a solutions but couldn't find related example. The problem is that space is skipping the reading to next variable so Marco is name and Beno is surname. However it should look like that: person.name == Marco Beno

SecretAgentMan
  • 2,856
  • 7
  • 21
  • 41

1 Answers1

0

Rather than reading the file line-by-line, you can use fscanf to read three lines (= one data record) at a time like this:

while (fscanf(filename, "%[^\n]\n%[^\n]\n%i\n", person1.name, person1.surname, &person1.age) == 3) 
{
    printf("Retrieved data record: name = '%s', surname = '%s', age = %i\n", 
        person1.name, person1.surname, person1.age);
}

The format specifier %[^\n]\n will read all characters except the newline character (i.e. an entire line including white spaces) and then the newline character itself. This happens twice per data record (for the name and surname), and finally it reads an integer number and the third newline character.

Note that this is just a simple example to explain the idea, and the person1 structure is overwritten every time. If you need the entire file in memory, you will of course have to store each data record individually (e.g. in an array of person).

Gerd
  • 2,568
  • 1
  • 7
  • 20