Thread: Why is it skipping scanf?

  1. #1
    Registered User
    Join Date
    May 2016
    Posts
    6

    Why is it skipping scanf?

    I've tried searching but can't find the answer I'm looking for. The program works the way it should until it asks "How many pages in the book?", it then skips the scanf(input). New to C programming. Any help?

    Code:
    #include <stdio.h>
    #include "bookinfo.h" 
    
    
    int main() {
    
    
      int ctr; 
      struct bookInfo books[3]; // Array of three structure variables
    
    
      // Get the information about each book from the user
      for (ctr = 0; ctr < 3; ctr++) { 
      	printf("What is the name of the book #%d?\n", (ctr+1)); 
      	fgets(books[ctr].title, sizeof(books), stdin); 
      	puts("Who is the author? "); 
      	fgets(books[ctr].author, sizeof(books), stdin); 
      	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 for next loops
      }	
    
    
      // Print a header line and then loop through and print the info
        printf("\n\nHere is the collection of books: \n"); 
      for (ctr = 0; ctr < 3; ctr++) {
        printf("#%d: %s by %s", (ctr+1), books[ctr].title, books[ctr].author); 
        printf("\nIt is %d pages and costs $%.2f", books[ctr].pages, books[ctr].price); 
        printf("\n\n"); 
      } 
    
    
    return 0; 
    
    
    }
    header file:
    Code:
    // Header File for Chapter 27, Program A
    
    
    struct bookInfo {
      char title[40]; 
      char author[25]; 
      float price; 
      int pages; 
    };

  2. #2
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    Are you entering the dollar sign at the previous prompt?

    Code:
    scanf(" $%f", &books[ctr].price);
    In fact, I suggest you just take the input without a dollar sign (i.e. remove '$' from your format string).

    Code:
    fgets(books[ctr].title, sizeof(books), stdin);
    The size of "struct bookInfo books" is not the same thing as the size of the member array variable "title". You likely want:

    Code:
    fgets(books[ctr].title, sizeof(books[ctr].title), stdin);
    Ditto for "author".

  3. #3
    Registered User
    Join Date
    May 2016
    Posts
    6
    Thank you, Matticus!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 11-30-2011, 09:59 AM
  2. ScanF Skipping The User Input.
    By XIIIX in forum C Programming
    Replies: 7
    Last Post: 10-11-2011, 07:00 AM
  3. Replies: 4
    Last Post: 05-26-2011, 06:51 AM
  4. Program skipping input....Scanf()
    By steve5591 in forum C Programming
    Replies: 2
    Last Post: 11-17-2010, 06:53 PM
  5. Skipping scanf()
    By Ican'tC in forum C Programming
    Replies: 4
    Last Post: 09-12-2002, 02:49 AM

Tags for this Thread