簡體   English   中英

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++。 您應該將std::cinstd::cout用於用戶 I/O。 std::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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM