This is my code:
#include <stdio.h>
struct book
{
char title[30];
char author[30];
char isbn[30];
float price;
}books[5];
int main()
{
int i=1,j=0;
while(i<6)
{
printf("Enter Title of Book No %d : ",i);
scanf("%[^\n]s",&books[j].title);
printf("Enter Author of Book No %d : ",i);
gets("%s",books[j].author);
i++;
j++;
}
printf("%s",books[3].author);
}
I keeps on getting segmentation fault while running the program. Any solution?
I first used gets and then tried Scanf instead of gets. I alsot tried declaring structure variable in the main function.
This is the error I'm getting:
$ ./a.out
Enter Title of Book No 1 : ttn ttr
zsh: segmentation fault ./a.out
Tried Using This code
#include <stdio.h>
struct book
{
char title[30];
char author[30];
char isbn[30];
float price;
}book;
int main()
{
int i=1,j=0;
struct book books[5];
while(i<6)
{
printf("Enter Title of Book No %d : ",i);
scanf("%[^\n]s",books[j].title);
printf("Enter Author of Book No %d : ",i);
scanf("%[^\n]s",books[j].author);
printf("Enter ISBN of Book no %d : ",i);
scanf("%[^\n]s",books[j].isbn);
printf("Enter Price of Book no %d : ",i);
scanf("%f",&books[j].price);
i++;
j++;
}
printf("%s",books[3].author);
}
but this only reads first scanf()
output :
Enter Title of Book No 1 : ads
Enter Author of Book No 1 : Enter ISBN of Book no 1 : Enter Price of Book no 1 : 54
Enter Title of Book No 2 : Enter Author of Book No 2 : Enter ISBN of Book no 2 : Enter Price of Book no 2 : 564
Enter Title of Book No 3 : Enter Author of Book No 3 : Enter ISBN of Book no 3 : Enter Price of Book no 3 : ^C
First of all, gets only take one argument.
Second of all, when scanf a string, you don't need to add &, because & means the address of. However, string is already passed by its address.
You should use
fgets(char *str, int n, FILE *stream)instead of gets, fgets can tell the program the char limit by n and where to read the input. For example : if you would like to read the input in stdin and the string limit is 50, you can usefgets(string, 50, stdin). Moreover, you should notice that fgets automatically add "\n" in the end of string, you can usestring[strcspn(string,"\n")] = 0to get rid of the "\n".The following modification works well in my device.