-4

Hello everyone I have made this simple program but there is some problem in taking input book name the program just skip the cin.get() function and then return 0, and I dont know why it's not working although there are no errors. any help would be appreciated. thank you

#include<iostream>
 using namespace std;
 struct book
 {
 private:
 int bookid;
 char name[30];
 float price;
 public: 
 input()
 {
    cout<<"\n Enter book ID: ";
    cin>>bookid;
 if(bookid<0)
 {
    bookid = -bookid;
 }
    cout<<"\nEnter book title: ";
    cin.get(name,30); // here is the problem
    cout<<"\nEnter book price: ";
    cin>>price;
 }
 display()
 {
    cout<<"\nBook ID: "<<bookid<<"\nbook title: "<<name<<"\nprice: "<<price;
 }
 };

 int main()
 {
 book b1;
 b1.input();
 b1.display();


 return 0;
 }
Waleed
  • 11
  • 1
  • 3

1 Answers1

0

Try making name a string rather than a character array, then use cin >> name; (for a single-word string) or cin.getline(name); (for a multi-word string). You will have to add #include <string> to the top of your program.

In general, don't use character arrays in C++ (that's more of a C thing).


EDIT:

I think your problem is here:

cin >> bookid; will stop when it detects a '\n' in the input stream, and then leave that \n in the stream. Then, when you call cin.getline(name); right after, the first character it will read is the '\n', and so it will immediately return because "it has read a line." This is a difference between cin >> and cin.getline().

So the solution is to replace cin.getline(name); with

cin.getline();
cin.getline(name);

That way it will get and discard the single '\n' (including any other whitespace that may precede the unwanted '\n') before reading the line actually containing the name.

If you know for a fact that the very next character is '\n' rather than some amount of other whitespace followed by a '\n', then you can just do cin.ignore(); to ignore the very next character, i.e. the '\n'.

Travis
  • 2,135
  • 17
  • 29