0

I use getline command in a while loop. The command works fine in the first loop. But after the second loop, it just passes the getline commands and doesn't allow me to enter

I tried cin.get and cin.getline but the problem is not fixed

#include <iostream>
#include <string>
#include <fstream>

using namespace std;


int price;

void addItem(){
    string product;
    cout << "Please enter product's name: " << endl;
    getline(cin, product);
    cout << "Please enter product's price: " ;
    cin >> price;
    cout << "You have added " << product << " with a price of $" << price << " to your cart." << endl;
}

int main() {
    char answer = 'y';
    int total = 0;
    while (answer == 'y'){
        addItem();
        total += price;
        cout << "Do you want to add another product (y/n)? " ;
        cin >> answer;
    }
    if (answer != 'y'){
        cout << "Your total is $" << total << endl;
    }
    return 0;

}
  • It's not a good idea to mix `cin >> ...` and `getline(cin, ...)`. That's where the problem is. The reason it's a problem is that `cin >> ...` **does not read newlines**. So you type 'y' followed by newline but only the 'y' is read. The newline isn't read until you get to the next `getline`. – john Apr 03 '19 at 08:45

2 Answers2

0

try

while(cin>>answer && answer !='y'){
    cout<<"enter again \n";
}
cout<<"ok";
barbsan
  • 3,238
  • 11
  • 18
  • 27
0

Mixing cin >> with getline(cin,...), so you should to avoid it. I assume that you used getline to read product name which contain spaces inside. You could rewrite your code to use only getline which should give you expected behavior:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;


int price = 0;

void addItem(){
  string product{};
  string price_str{};
    cout << "Please enter product's name: " << endl;
        getline(cin, product);
    cout << "Please enter product's price: " ;
    getline(cin,price_str);

    /*CHECK IF price_str is number before calling stoi*/

    price = stoi(price_str);
    cout << "You have added " << product << " with a price of $" << price << " to your cart." << endl;
}

int main() {
    string  answer = "y";
    int total = 0;
    while (answer == "y"){
        addItem();
        total += price;
        cout << "Do you want to add another product (y/n)? " ;
        getline(cin,answer);

    }
    if (answer != "y"){
        cout << "Your total is $" << total << endl;
    }
    return 0;

}


KPR
  • 91
  • 6