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

How to make getline command work in a while loop?

本文关键字:循环 工作 while 何使 getline 命令      更新时间:2023-10-16

我在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;
}

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

试试

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