Reputation: 17
I'm using C for reading text from file and store it in array of struct. But after I print it using printf, it's output is not what i expected.
My Code:
#include<stdio.h>
struct userINFO {
char id[6];
char name[20];
char lastName[20];
};
int main()
{
FILE *fdata;
struct userINFO allUser[3];
int i=0;
fdata = fopen("textdata.txt","r");
if (fdata == NULL)
{
printf("ERROR!");
return 0;
}
while (fscanf(fdata,"%s %s %s", allUser[i].id, allUser[i].name, allUser[i].lastName)!=EOF)
{
i++;
}
for (i = 0; i < 3 ; i++)
{
printf("ID: %s\n", allUser[i].id);
printf("Name: %s\n", allUser[i].name);
printf("LastName: %s\n", allUser[i].lastName);
}
fclose(fdata);
return 0;
}
Text File:
001001
Firstname1
LastName1
601002
Firstname2
LastName2
601003
Firstname3
LastName3
Output
ID: 001001Firstname1
Name: Firstname1
LastName: LastName1
ID: 601002Firstname2
Name: Firstname2
LastName: LastName2
ID: 601003Firstname3
Name: Firstname3
LastName: LastName3
What it should be:
ID: 001001
Name: Firstname1
LastName: LastName1
ID: 601002
Name: Firstname2
LastName: LastName2
ID: 601003
Name: Firstname3
LastName: LastName3
I have tried many thing like change fscanf -> fgets, add %6s in printf, change text format etc. But its output still be the same. What should i change in my code to make it display correctly?
Upvotes: 0
Views: 47
Reputation: 284
In the struct you are using an string of length 6 but you need to take in consideration the '\0' character. So making the id length as 7 will solve your problem
#include<stdio.h>
struct userINFO {
char id[7];
char name[20];
char lastName[20];
};
int main()
{
FILE *fdata;
struct userINFO allUser[3];
int i=0;
fdata = fopen("textdata.txt","r");
if (fdata == NULL)
{
printf("ERROR!");
return 0;
}
while (fscanf(fdata,"%s %s %s", allUser[i].id, allUser[i].name, allUser[i].lastName)!=EOF)
{
i++;
}
for (i = 0; i < 3 ; i++)
{
printf("ID: %s\n", allUser[i].id);
printf("Name: %s\n", allUser[i].name);
printf("LastName: %s\n", allUser[i].lastName);
}
fclose(fdata);
return 0;
}
Upvotes: 1
Reputation: 31296
Simple. Change:
struct userINFO {
char id[6];
char name[20];
char lastName[20];
};
to
struct userINFO {
char id[7];
char name[20];
char lastName[20];
};
In C, you need one extra character for a \0
that indicates the end of the string.
C is pretty lowlevel, so printf
does not know how much memory that is reserved for a string. The only thing printf
knows is where it starts. It then continue to read until it hits \0
. If it reads outside the array it causes undefined behavior.
Upvotes: 0