0

I am following a C coding lesson but when I've attempted to execute the example program on putting data into structured variables it does not work properly. The last scanf is skipped and it moves back to the beginning of the loop. I attempted a different example program with a similar structure and received the same results. Please let me know if you have any suggestions. Thanks

for (ctr = 0; ctr < 3; ctr++)
{
    printf("What is the name of the book #%d?\n", (ctr+1));
    gets(books[ctr].title);
    puts("Who is the author? ");
    gets(books[ctr].author);
    puts("How much did the book cost? ");
    scanf(" $%f", &books[ctr].price);
    puts("How many pages in the book? ");
    scanf(" %d", &books[ctr].pages);
    getchar(); //Clears last newline of the next loop

Code Code execution

Tincan
  • 1
  • `gets` is deprecated in C; do NOT use it. Use `fgets` or `getline` instead. – SGeorgiades Mar 05 '22 at 04:23
  • I'd venture that the first scanf is leaving a newline in the input buffer. – G4143 Mar 05 '22 at 04:51
  • 2
    Check the return value of each `scanf`. I think you will find that the first `scanf` is failing to match. It expects a `$` which is not present in the inputted value. – kaylum Mar 05 '22 at 05:29
  • See [Why `gets()` is so dangerous it should never be used!](https://stackoverflow.com/q/1694036/15168) – Jonathan Leffler Mar 05 '22 at 05:34
  • By removing the $ from the first scanf has cleared the issue up. I've also updated the gets to fgets. Thanks for the help. – Tincan Mar 06 '22 at 14:39

0 Answers0