I need some help with an assignement I have to do for school which consists in sorting some books after the title,author and the publication date of it. All the infos are given as a string in a txt file using a delimiter between them. The problem is that I don't manage to properly read the data, my program crashes after I try to perform a strcpy(). Can you guys help me with this and tell me what have I done wrong?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct book
{
char author[100],title[100];
int year;
};
int main()
{
struct book b[25];
int i,n;
char intro[25][150],*p;
const char delim[2] = "#";
FILE *fp;
fp=fopen("text.txt", "r");
fscanf(fp,"%d",&n);
for(i=0;i<=n;i++)
{
fgets(intro[i], sizeof (intro[i]), fp);
p=strtok(intro[i], delim);
strcpy(b[i].title,p);
p=strtok(NULL, delim);
strcpy(b[i].author,p); /// The program works until it reaches this point - after performing this strcpy() it crashes
if(p!=NULL)
{
p=strtok(NULL,delim);
b[i].year=atoi(p);
}
}
return 0;
}
An example of input could be this:
5
Lord Of The Rings#JRR Tolkien#2003
Emotional Intelligence#Daniel Goleman#1977
Harry Potter#JK Rowling#1997
The Foundation#Isaac Asimov#1952
Dune#Frank Herbert#1965