C ++:程序在获取输入字符串的过程中终止

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

我的程序正在接受用户的字符串输入。使用 fgets() 函数,但我也尝试了 gets()scanf("%[^\n]s", str),但程序仍然在一半时终止。

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;
}

程序在仅接受两个输入后终止。

这是输出:

Publisher: Pearson
Title: The power of subconcious mind

您没有分配任何内存来读取用户输入。您的 char*Book* 指针未初始化,没有指向任何有意义的地方。

试试这个:

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;

话虽这么说,将 C 习语与 C++ 习语混合是个坏主意。拥抱 C++。您应该为用户 I/O 使用 std::cinstd::coutstd::string 而不是 char[] 字符串。和智能指针而不是原始指针。

试试这个:

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