[英]C++: Program get terminated at mid of taking input string
My program is taking string input from the user.我的程序正在从用户那里获取字符串输入。 Using the
fgets()
function, but also I tried gets()
and scanf("%[^\\n]s", str)
, but still the program get terminated at half.使用
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;
}
Program gets terminated after taking only two inputs.程序在仅接受两个输入后终止。
Here is the output:这是输出:
Publisher: Pearson
Title: The power of subconcious mind
You are not allocating any memory to read the user input into.您没有分配任何内存来读取用户输入。 Your
char*
and Book*
pointers are uninitialized and don't point anywhere meaningful.您的
char*
和Book*
指针未初始化并且没有指向任何有意义的地方。
Try this instead:试试这个:
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;
That being said, it is a bad idea to mix C idioms with C++ idioms.话虽如此,将 C 习语与 C++ 习语混合在一起是个坏主意。 Embrace C++.
拥抱 C++。 You should be using
std::cin
and std::cout
for user I/O.您应该将
std::cin
和std::cout
用于用户 I/O。 And std::string
rather than char[]
strings.和
std::string
而不是char[]
字符串。 And smart pointers rather than raw pointers.和智能指针而不是原始指针。
Try this:尝试这个:
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.