I am new to C, so I am likely not implementing the advice regarding removing trailing newlines located here correctly, but I have experimented for about an hour now and I'm still confused.
Here's the basic program, it's from a C Programming Absolute Beginner's Guide.
4 main()
5 {
6 int ctr;
7 char c;
8 struct bookInfo books[3]; // array of three structure variables
9
10 // get info about each book from user
11 for (ctr = 0; ctr < 3; ctr++)
12 {
13 printf("What is the name of book #%d?\n", (ctr+1));
14 fgets(books[ctr].title, sizeof(books[ctr].title), stdin);
15 books[ctr].title[strcspn(books[ctr].title, "\r\n")] = 0;
16
17 puts("Who is the author? ");
18 fgets(books[ctr].author, sizeof(books[ctr].title), stdin);
19 books[ctr].author[strcspn(books[ctr].author, "\r\n")] = 0;
20
21 puts("How much did the book cost? ");
22 scanf(" $%f", &books[ctr].price);
23
24 puts("How many pages in the book? ");
25 scanf(" %d", &books[ctr].pages);
26 }
The book uses gets()
for lines 14 and 18, but I have done enough reading to know that this is not good and have replaced it with fgets()
. I feel like I am misunderstanding how either strcspn()
works, or how scanf()
interacts with the results of the previous code.
The top-voted answer to the link I've referenced above specifically uses this strcspn()
technique:
books[ctr].title[strcspn(books[ctr].title, "\r\n")] = 0;
as
buffer[strcspn(buffer, "\n")] = 0;
but clearly I am not implementing this correctly. I wondered if it had something to do with the Struct, but I doubt that.
I also tried just capturing the extra input in the buffer in this way:
3 printf("What is the name of book #%d?\n", (ctr+1));
14 fgets(books[ctr].title, sizeof(books[ctr].title), stdin);
15 getchar();
but I get the same behavior.
Here's my output:
What is the name of book #1?
hobbit
Who is the author?
tolkien
How much did the book cost?
14.99 <-- scanf() captures the newlines
How many pages in the book? <-- this scanf() gets "skipped"
What is the name of book #2?
Who is the author?