如何使 getline 命令在 while 循环中工作
How to make getline command work in a while loop?
我在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";
相关文章:
- 当我在第一个循环中使用"auto"时,它工作正常,但是使用"int"它会给出错误,为什么?
- 循环仅对第一行正常工作.其他行不受 for 的影响
- 当输入在带有空格的单行中给出时,cin 如何在 while 循环中工作?
- C++中循环和 C 样式数组的范围工作
- 在循环工作时,首先将两个文件读为向量,但仅次于迭代一次
- 试图让while循环工作,当输入符号而不是字符时会中断
- 循环工作时如何做到这一点?
- 有问题使循环工作与功能相结合
- 无法让 for 循环工作
- do while循环工作不正常
- c++不要循环工作
- 循环工作/不起作用,不知道为什么C++
- C++While循环工作
- c++:循环时出现TypeError,但在循环工作之前-(已修改)LinkedListClass迭代
- 循环工作不正常
- 什么代码可以使这个循环工作
- 我应该如何让我的for循环工作?for循环是全新的
- 我如何使这个循环工作
- 可以根据分配的循环工作范围
- Windows 8 APP,用数据绑定改变XAML文本框的文本.游戏循环工作线程导致问题