0

When i Compile this program then i can't input book2.title name, is it fault about using gets funtion then why? please explain it more ...........................

#include<stdio.h>
#include<string.h>
struct name{
char author[20];
char title[20];
float price;
};
int main()
{
    struct name book1,book2;
    printf("Enter 1st title name:");
    gets(book1.title);
    printf("Enter 1st Author name:");
    gets(book1.author);
    printf("Enter 1st Book price:");
    scanf("%f",&book1.price);
    printf("\nThe 1st Book Name is %s",book1.title);
    printf("\nThe 1st Book Author is %s",book1.author);
    printf("\nThe 1st Book Price is %f",book1.price);
    printf("\nEnter 2nd title name:");
    gets(book2.title);
    printf("Enter 2nd Author name:");
    gets(book2.author);
    printf("Enter 2nd Book price:");
    scanf("%f",&book2.price);

    printf("\nThe 2nd Book Name is %s",book2.title);
    printf("\nThe 2nd Book Author is %s",book2.author);
    printf("\nThe 2nd Book Price is %f",book2.title);
     return 0;


}


1 Answers1

2

Your code has two problems unrelated to your question:

  • The use of gets
  • The use of %f in printf for a string.

However, the behavior leading to your question lies in these two lines:

scanf("%f",&book1.price);
...
gets(book2.title);

Note, when you enter the book1 price (say 12.3) in the terminal, you press enter afterwards. Therefore, the stdin buffer holds the characters 12.3\n. The scanf reads the first few bytes which it can interpret as a float 12.3, leaving the buffer holding \n. Now, when you run gets, it reads the newline, and your 2nd book's title is the blank string "\0".

See this website: https://www.geeksforgeeks.org/problem-with-scanf-when-there-is-fgetsgetsscanf-after-it/

Note: Please, please use fgets/scanf/getline instead of gets. For more information, see the link posted by @RobertS in the comments above.

TSG
  • 877
  • 1
  • 6
  • 23