【发布时间】: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