Question

I have the following struct

typedef char String[256];

typedef struct
{
    String name;
    int year;
    float price;
} Book;

Array of Books

int main(int argc, const char * argv[])
{    
    Book books[5];

    for (int i=0; i<5; i++) {
        books[i] = inputBook();
    }

    return 0;
}

inputBook() function

Book inputBook()
{
    Book myBook;

    //Name
    puts("Enter Book Name:");
    gets(myBook.name);

    //Publishing Year
    puts("Enter Book Publishing Year:");
    scanf("%i", &myBook.year);

    //Price
    puts("Enter Book Price:");
    scanf("%f", &myBook.price);

    return myBook;
}

For some reason the first book input is going well but when trying to input the second book and the second call to inputBook() I can set a book name, it jumps straight to the year import.

What is the problem ?

Thanks!

Was it helpful?

Solution

To correct, replace:

gets(myBook.name);

with:

scanf("%255s", myBook.name); /* 255 as name is 256 chars. */

as scanf() will skip any whitespace characters, but gets() will not. A newline character is considered a whitespace character and there will be a newline remaining in stdin after the price has been entered causing gets() to read the newline and effectively read nothing.

Worth reading: warning:gets function is dangerous

OTHER TIPS

This is because the variable myBook is valid only in the inputBook scope and is destroyed as soon as the function exits.

you should pass the book item you want to initialize as a parameter of your function.

function inputBook()...

void inputBook(Book *ptBook )
{
    if( ptBook==NULL )
        return;

    //Name
    puts("Enter Book Name:");
    gets(ptBook->name);

    //Publishing Year
    puts("Enter Book Publishing Year:");
    scanf("%i", &ptBook->year);

    //Price
    puts("Enter Book Price:");
    scanf("%f", &ptBook->price);
}

The main function...

int main(int argc, const char * argv[])
{    
    Book books[5];

    for (int i=0; i<5; i++) {
        inputBook( &books[i] );
    }

    return 0;
}

I think you need to flush stdin before next iteration. You have orevious CRLF in your stdin stream.

use fflush(stdin); in the beginning of loop.

Maybe you can try fflush(stdin) before input.

Book inputBook()
{
    Book myBook;

    fflush(stdin);

    // rest of the code
}
#include <stdio.h>

typedef char String[256];

typedef struct
{
    String name;
    int year;
    float price;
    } Book;
Book inputBook()
{
    Book myBook;

    //Name
    puts("Enter Book Name:");
    getchar();
    gets(myBook.name);

    //Publishing Year
    puts("Enter Book Publishing Year:");
    scanf("%i", &myBook.year);

    //Price
    puts("Enter Book Price:");
    scanf("%f", &myBook.price);

    return myBook;
}
int main(int argc, const char * argv[])
{
    Book books[5];

int i = 0; for (i=0; i<5; i++) {
    books[i] = inputBook();
}

return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top