[英]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::cin
和std::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.