【问题标题】:C++: Program get terminated at mid of taking input stringC ++:程序在获取输入字符串的中间终止
【发布时间】:2021-12-04 08:34:09
【问题描述】:

我的程序正在从用户那里获取字符串输入。使用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

【问题讨论】:

  • 在 c++ 中使用 std::string 变量而不是原始 c 样式 char* 指针。 printf()fgets() 对于 c++ 代码也不是很惯用。我有一种感觉,你,或者其他人,正试图让你的生活变得比实际更艰难????
  • 您知道char 指针声明不会分配char 数组吗?出于类似的原因,Book* new_book; 不会实例化Book,因此复制/移动分配也是一个问题。遵循@πάνταῥεῖ 建议并避免指点。

标签: c++ string input char buffer


【解决方案1】:

您没有分配任何内存来读取用户输入。您的 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    相关资源
    最近更新 更多