I am making a C++ program to handle books. The user needs to insert the title, price and volumes for 3 books. I don't include the Book
class in the code as it is not relevant with my problem.
I am stuck in the place where the user needs to input the values inside the loop. When I test the program the console keeps bugging at seemingly random times. (i.e. it shows "Give book p"
instead of the full sentence and awaits for input).
I read in other answers that I should use cin.ignore()
after every cin>>
call in order to ignore the \n
that is put on the stream when the user presses enter, but it doesn't solve my problem?
Any ideas what I am doing wrong?
#include <iostream>
#include <sstream>
using namespace std;
int main() {
string title;
double price;
int volumes;
for (int i=0; i<3;i++){
cout << "Give book title : " << endl;
getline (cin, title);
cout << "Give book price : " << endl;
cin >> price;
cin.ignore();
cout << "Give number of volumes : " << endl;
cin >> volumes;
cin.ignore();
}
return 0;
}
Following is an example of the console :
Give book title : The Hobbit The Hobbit Give book price : 12.5 12.5 Give number of volumes : 10 10 Give book title : Lord of the Rings Lord of the Rings Give book price : 12 12 Give number of volumes : 7 7 Give bo
As you can see the last sentence is cut off and the console is stuck after.