c++While循环打印couts两次
c++ While loops prints the couts twice
在我的代码中,while循环打印cout两次,而它应该打印一次,以及函数的cout。我不明白它为什么这么做——它应该显示
你想做什么?
存款
提取
取消
但是,它显示了两次。
while (yesNo == 'Y') {
cout << "What would you like to do?"
<< endl
<< endl;
menu();
getline(cin, bankChoice);
if (bankChoice == "Withdraw")
{
withdrawTotal = withdraw(bankAmount);
bankAmount = withdrawTotal;
cout << "You now have $"
<< bankAmount
<< " in your account."
<< endl;
cout << "Would you like to do anything else?"
<< endl
<< "Y/N: ";
cin >> yesNo;
}
if (bankChoice == "Deposit")
{
depositTotal = deposit(bankAmount);
bankAmount = depositTotal;
cout << "You now have $"
<< bankAmount
<< " in your account."
<< endl;
cout << "Would you like to do anything else?"
<< endl
<< "Y/N: ";
cin >> yesNo;
}
if (bankChoice == "Cancel") {
return 0;
}
}
这就是我正在使用的循环。如果需要额外的代码,我也可以发布,但这是导致问题的部分。我尝试过不使用它的代码,它运行良好,但我希望让代码循环,直到用户输入"N"。
您同时使用std::getline
和operator>>
读取std::cin
。operator>>
不使用后面的换行符,因此对std::getline
()的下一次调用将立即读取下面的换行符并将其解释为输入的空文本行。这将贯穿整个循环,并返回到顶部,以获得第二个提示。
当您打算阅读一行文本时,切勿将operator>>
与std::cin
一起使用。
下面的简短示例说明了这一点:
#include <iostream>
#include <string>
int main()
{
char c;
std::string l;
std::cin >> c;
std::cout << "A line of text please: ";
std::getline(std::cin, l);
}
运行它,输入"Y",试着自己弄清楚程序立即终止的原因。
再次:不要使用operator>>
来读取std::cin
中的文本行。这是悲伤和虫子的配方。
除了Sam的答案之外,我还建议您提取两个if语句之外的通用功能:
std::string yesNo;
while (yesNo.compare("Y") == 0) {
cout << "What would you like to do?"
<< endl
<< endl;
menu();
getline(cin, bankChoice);
if (bankChoice == "Cancel")
return 0;
if (bankChoice == "Withdraw") {
withdrawTotal = withdraw(bankAmount);
bankAmount = withdrawTotal;
}
if (bankChoice == "Deposit") {
depositTotal = deposit(bankAmount);
bankAmount = depositTotal;
}
cout << "You now have $"
<< bankAmount
<< " in your account."
<< endl;
cout << "Would you like to do anything else?"
<< endl
<< "Y/N: ";
std::getline(std::cin, yesNo);
}
相关文章:
- g++的分段错误(在NaN上使用to_string两次时)
- 蛇在C++不会连续转两次
- 检查一个数组是否包含在另一个数组中,以相反的顺序,至少两次
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- 我应该如何去缓解两次出现的cin?
- Realloc 两次无法在 Visual Studio 上运行
- 使用 getline(cin, var) 两次在进行字符串比较时会产生错误 (==)
- 为什么映射插入和 map.find() 的单次迭代比插入和 map.find() 的两次单独迭代慢得多
- C++析构函数调用两次,堆栈分配的复合对象
- 为什么参数在构造 std::thread 时移动两次
- Qt插槽调用了两次
- 做 std::用相同的unique_ptr移动两次
- C++两次定义相同的函数会导致错误
- 为什么具有静态存储持续时间的同一内联变量在包含在 VS2017 编译的两个翻译单元中时会构造和销毁两次
- 对于优化级别为 0 的 std::vector,析构函数被调用两次
- 使用柯南打包时如何避免列出两次依赖?
- 为什么要执行两次位移((x >> 4)<< 4)?
- 对结构向量进行两次排序
- 如果我使用同一个密钥推送用户数据两次,会发生什么
- c++While循环打印couts两次