我不知道为什么这个循环出现故障
I Can't Figure Out Why This Loop Is Malfunctioning
所以我就是想不出我的代码出了什么问题。 当我处理购买时,在我输入酸奶量并被告知去享用它之后,如果人们不输入 P 或 S,我会立即收到我制作的错误消息,然后它立即恢复正常,就像您第一次进入程序时一样,谁能告诉我为什么会这样? 谢谢!
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string userCommand;
int creditCount = 0;
int userInput;
while (creditCount >= 0)
{
cout << "--------Menu--------n" << "P (Process Purchase)n" << "S (Shutdown System)n"
<< "--------Menu--------n" << "Your Choice: ";
getline(cin, userCommand);
if (userCommand[0] == 'P' || userCommand[0] == 'p')
{
if (creditCount >= 10)
{
cout << "You qualify for a free yogurt, would you like to use ten of your credits (Yes or No)?";
getline(cin, userCommand);
if (userCommand[0] == 'Y' || userCommand[0] == 'y')
{
creditCount = creditCount - 10;
cout << "You just used 10 credits and now have " << creditCount << " left.n"
<< "Enjoy your free yogurt!";
}
else if (userCommand[0] == 'N' || userCommand[0] == 'n')
{
cout << "How many yogurts would you like to buy? ";
cin >> userInput;
if (userInput > 0)
{
creditCount = creditCount + userInput;
cout << "You just earned " << userInput << " stamps. You now have " << creditCount
<< " credits! Enjoy your yogurt!";
}
else
{
cout << "Invalid input, please try processing your purchase again and enter a positive "
<< "integer.";
}
}
else
{
cout << "*Error, please try processing your purchase again and enter either Yes or No*nn";
}
}
else if (creditCount < 10)
{
cout << "How many yogurts would you like to buy? ";
cin >> userInput;
if (userInput > 0)
{
creditCount = creditCount + userInput;
cout << "You just earned " << userInput << " stamps. You now have " << creditCount
<< " credits! Enjoy your yogurt!nn";
}
else
{
cout << "Invalid input, please try processing your purchase again and enter a positive "
<< "integer.";
}
}
}
else if (userCommand[0] == 'S' || userCommand[0] == 's')
{
cout << "*Shutting down system*n";
return 0;
}
else
{
cout << "*Error, please enter either P (for Process Purchase) or S (for Shutdown System)*nn";
}
}
}
@acid1789正确地指出错误是由于getline之后的空行造成的。从你的代码中我能看出你在这里使用了一个无限循环
while(creditCount >= 0){...}
因为 creditCount 永远不会小于 0,而不是这个你可以使用
while (true){...}
它只是更好的编程实践。
要纠正您的程序,您只需使用
cin >> userCommand;
而不是
getline(cin, userCommand);
希望对您有所帮助。
编辑:- 对不起蟒蛇习惯..
这里的问题是getline返回一个空行。
因此,在您第一次通过循环后,它会回到顶部以阅读另一行。 获取一个空行,这将触发错误情况。
您可以通过在 getline 之后测试空行来解决此问题。
相关文章:
- 如何循环打印顶点结构
- 分段故障(堆芯转储)矢量
- 循环C 的分割故障OpenMP
- C 查找无SQRT函数循环故障的平方根
- 在循环的末尾获取细分故障
- 循环C++中的分段故障
- 循环中的数组出现故障
- 循环后出现分段故障
- C++:使用嵌套的 if/else 语句循环进行故障排除
- 我不知道为什么这个循环出现故障
- ENTERING循环时出现分段故障
- C++:对循环进行故障排除
- While循环中的C++分段故障
- 循环打印时出现分段故障
- 函数检查出边界/分割故障在二维循环
- 当迭代通过大串集时,for循环接收到信号SIGSEGV,出现分段故障
- c++分割故障及循环函数
- 循环时出现分段故障
- 迭代器,循环导致seg故障!为什么循环太多
- C++容器上的分段故障循环