4

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.

Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
thelaw
  • 570
  • 4
  • 14

1 Answers1

0

You can use std::ws as a parameter to your getline() method to achieve your objective.

The following code will serve your purpose:

#include <iostream>

int main() {
    std::string title;
    double price;
    int volumes;

    for (int i=0; i<3;i++){
        std::cout << "Give book title : ";
        std::getline(std::cin >> std::ws, title);
        std::cout << "Give book price : ";
        std::cin >> price;
        std::cout << "Give number of volumes : ";
        std::cin >> volumes;
        std::cout<<"Title: "<<title<<" costs "<<price<<" for "<<volumes<<" volumes.\n";
    }

     return 0;
}

This will produce the following output:

Give book title : Harry Potter
Give book price : 12.5
Give number of volumes : 5
Title: Harry Potter costs 12.5 for 5 volumes.
Give book title : James Anderson
Give book price : 45.6
Give number of volumes : 7
Title: James Anderson costs 45.6 for 7 volumes.
Give book title : Lucas Empire
Give book price : 34.5
Give number of volumes : 7
Title: Lucas Empire costs 34.5 for 7 volumes.
Praveen Vinny
  • 2,372
  • 6
  • 32
  • 40