我的程式正在從用戶那里獲取字串輸入。使用該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
uj5u.com熱心網友回復:
您沒有分配任何記憶體來讀取用戶輸入。您的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
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/321786.html
上一篇:從命令列引數操作字串
