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.
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
CodePudding user response:
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.
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. Embrace C . You should be using std::cin
and std::cout
for user I/O. And std::string
rather than char[]
strings. 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