如何使getline命令在while循环中工作?

时间:2019-04-03 08:16:13

标签: c++

我在while循环中使用getline命令。该命令在第一个循环中工作正常。但是在第二个循环之后,它只是传递了getline命令,并且不允许我输入

我尝试了cin.get和cin.getline,但问题未解决

#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;

}

2 个答案:

答案 0 :(得分:0)

cin >>getline(cin,...)混合,因此应避免使用它。我假设您使用getline来读取产品名称,其中包含空格。您可以重写代码以仅使用getline,这应该会给您带来预期的行为:

#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;

}


答案 1 :(得分:-1)

尝试

while(cin>>answer && answer !='y'){
    cout<<"enter again \n";
}
cout<<"ok";