简体   繁体   中英

skipping over scanf loops in c

I don't know why, when I run this, it skips the "how many pages in the book" scanf and goes straight onto the second loop "who is the author".

I'm sure this is something to do with whitespace, but I thought I accounted for this with the getchar at the bottom of the for loop.

header:

struct bookInfo{
  char title[40];
  char author[25];
  float price;
  int pages;
}; 

.c file:

int main()
{
  int ctr;
  struct bookInfo books[3]; 
  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 books cost");
    scanf(" $%f", &books[ctr].price);
    puts("how many pages in the book");
    scanf(" %d", &books[ctr].pages);
    getchar();
  }

  printf("here is the collection of books: \n");
  for (ctr = 0; ctr <3; ctr++)
  {
    printf("book #%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);
  }
  return 0;
}

Change this:

puts("how much did the books cost");
scanf(" $%f", &books[ctr].price);

to this:

printf("how much did the books cost: $");
fflush( stdout );
scanf("%f", &books[ctr].price);

Unless you intend for your user to type a $ before the price, which would be annoying. You don't need the leading blank in the format string, since %f tells scanf to skip over leading whitespace.

Secondly, NEVER NEVER NEVER NEVER NEVER NEVER NEVER NEVER use gets . Ever. In any way, shape, or form. It will (not might, will ) introduce a point of failure / major security hole in your program. It was deprecated in the 1999 standard, and has been removed from the standard library as of the 2011 standard. It is the programming equivalent of splicing live wires while standing in a shower.

Use fgets (which, unlike gets , will attempt to store the newline character in the target buffer if there's room) or scanf (with an appropriate precision in the conversion specifier) instead.

That is because gets() reads the line of text present in the current buffer. and since the current buffer contains "What is name of author ?" it reads it.

If you display the contents of the struct members you can clearly observe this.

So I Suggest this Use

    char *temp;
    fgets(STDIN,temp);

before Loop begins.

This helps you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM