简体   繁体   中英

C++: Program get terminated at mid of taking input string

My program is taking string input from the user. Using the fgets() function, but also I tried gets() and scanf("%[^\\n]s", str) , but still the program get terminated at half.

Book* create_book()
{
    Book* new_book;
    char* title;
    char* author;
    char* publisher;
    double price;
    int stock;

    printf("\nPublisher: ");
    fgets(publisher, 50, stdin);
    printf("\nTitle: ");
    fgets(title, 50, stdin);
    printf("\nAuthor: ");
    fgets(author, 50, stdin);
    printf("\nPrice: ");
    cin >> price;
    printf("\nStock Position: ");
    cin >> stock;


    *new_book = Book(author, title, publisher, price, stock);
    printf("\nCreated");
    return new_book;
}

Program gets terminated after taking only two inputs.

Here is the output:

Publisher: Pearson
Title: The power of subconcious mind

You are not allocating any memory to read the user input into. Your char* and Book* pointers are uninitialized and don't point anywhere meaningful.

Try this instead:

Book* create_book()
{
    Book* new_book;
    char title[50];
    char author[50];
    char publisher[50];
    double price;
    int stock;

    printf("\nPublisher: ");
    fgets(publisher, 50, stdin);
    printf("\nTitle: ");
    fgets(title, 50, stdin);
    printf("\nAuthor: ");
    fgets(author, 50, stdin);
    printf("\nPrice: ");
    cin >> price;
    printf("\nStock Position: ");
    cin >> stock;

    new_book = new Book(author, title, publisher, price, stock);
    printf("\nCreated");
    return new_book;
}
Book *book = create_book();
// use book as needed...
delete book;

That being said, it is a bad idea to mix C idioms with C++ idioms. Embrace C++. You should be using std::cin and std::cout for user I/O. And std::string rather than char[] strings. And smart pointers rather than raw pointers.

Try this:

unique_ptr<Book> create_book()
{
    unique_ptr<Book> new_book;
    string title;
    string author;
    string publisher;
    double price;
    int stock;

    cout << "\nPublisher: ";
    getline(cin, publisher);
    cout << "\nTitle: ";
    getline(cin, title);
    cout << "\nAuthor: ";
    getline(cin, author);
    cout << "\nPrice: ";
    cin >> price;
    cout << "\nStock Position: ";
    cin >> stock;

    new_book = make_unique<Book>(author, title, publisher, price, stock);
    cout << "\nCreated";
    return new_book;
}
auto book = create_book();
// use book as needed...
// no delete needed

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