When I was working on the C Programming Language, I wanted to do a little program to revise these previous knowledge points. And this is the program which it seems there are some problems with it.
This program is supposed to collect information from input and print it in the file "reg.txt" in a format.
However, after typing the first line and press the enter, the program quits, but I can't figure it out what's wrong with it.
#include <stdio.h>
int main()
{
FILE *fp;
struct profile
{
char *name;
char *surname;
int year;
int month;
int day;
} people[10];
int temp;
int i = 0;
char *line;
fp = fopen("reg.txt", "a");
while (fgets(line, 256, stdin)
{
sscanf(line, "%s %s %d/%d/%d", people[i].name, people[i].surname, &(people[i].year), &(people[i].month), &(people[i].day));
++i;
}
temp = i-1;
for (i = 0; i <= temp; ++i)
fprintf(fp, "NAME: %s %s\nBIRTHDAY: %d/%d/%d\n", people[i].name, people[i].surname, people[i].year, people[i].month, people[i].day);
fclose(fp);
return 0;
}
I've taken Ed Heal's advice and I was aim to check the return value of 'sscanf'. What's strange is that the program doesn't really reach the 'printf' part. I thought may there are some problems with the loop?
#include <stdio.h>
int main()
{
FILE *fp;
void filecopy(FILE *, FILE *);
struct profile
{
char *name;
char *surname;
int year;
int month;
int day;
} people[10];
int temp;
int i = 0;
char *line;
int j;
fp = fopen("reg.txt", "a");
while (fgets(line, 256, stdin) != NULL)
{
j = sscanf(line, "%s %s %d/%d/%d", people[i].name, people[i].surname, &(people[i].year), &(people[i].month), &(people[i].day));
++i;
}
temp = i-1;
//for (i = 0; i <= temp; ++i)
// fprintf(fp, "NAME: %s %s\nBIRTHDAY: %d/%d/%d\n", people[i].name, people[i].surname, people[i].year, people[i].month, people[i].day);
printf("%d",j);
fclose(fp);
return 0;
}