好的,这是一个简单的代码示例:
char answer;
cin >> answer;
switch(answer)
{
case 'y':
case 'Y':
inventory[0] = "Short Sword";
cout << "\nYou place the Rusty Battle Axe in the chest.";
break;
case 'n':
case 'N':
inventory[0] = "Rusty Battle Axe";
cout << "\nYou leave the Short Sword in the chest.";
break;
default :
cout << "\nThat was an invalid response.";
}
显然,我可以花一会儿时间(回答!='Y'||回答!=...)但是有没有更优雅的方法可以在执行默认案例后简单地返回第一个案例?因此,如果用户输入了错误的字母,我只需再次问他们问题,直到他们输入可接受的回复?
不,这不是家庭作业或任何东西。我正在阅读 Dawson 的 C++ Game Programming 一书,我想通过允许用户保留或交易物品来使程序示例更加生动。我把这一切都做得很好,但是如果输入了错误的响应,它只会显示库存的内容并退出。我想做到这一点。强制用户输入正确的响应,然后显示更新后的库存。
感谢帮助!
更新! 你们都给了我很多不同的方法——我真的很感激!我承认我可能没有正确设计这个 switch 语句,我为这个矛盾道歉。我会尝试你的每一个建议并在这里发回,选择一个作为答案。谢谢!
好的,我刚刚浏览了你所有的答案,并用我的代码尝试了其中的大部分。我选择了最简单、最优雅的解决方案作为我问题的答案。但是你们都帮助我看到了看待这个问题的不同方式,而且我现在对 switch 语句有了更多的了解。实际上,在我正在 YouTube 上由用户 What's A Creel 关注的教程中使用它来代替 while 循环
我真的很感谢你的帮助!我觉得我今天在编程实践中确实取得了很多成就。你们(和女孩)都很棒!
更新和完整的代码:
#include <iostream>
#include <string>
using namespace std;
// This program displays a hero's inventory
int main()
{
const int MAX_ITEMS = 4;
string inventory[MAX_ITEMS];
int numItems = 0;
inventory[numItems++] = "Rusty Battle Axe";
inventory[numItems++] = "Leather Armor";
inventory[numItems++] = "Wooden Shield";
cout << "Inventory:\n";
for(int i = 0; i < numItems; ++i)
{
cout << inventory[i] << endl;
}
cout << "\nYou open a chest and find a Lesser Healing Potion.";
inventory[numItems++] = "Lesser Healing Potion";
cout << "\nInventory\n";
for(int i = 0; i < numItems; ++i)
{
cout << inventory[i] << endl;
}
cout << "\nYou also find a Short Sword.";
if(numItems < MAX_ITEMS)
{
inventory[numItems++] = "Short Sword";
}
else
{
cout << "\nYou have too many items and can't carry another.";
cout << "\nWould you like to trade the " << inventory[0] << " for the Short Sword? ";
}
while (true)
{
char answer;
cin >> answer;
switch(answer)
{
case 'y':
case 'Y':
inventory[0] = "Short Sword";
cout << "\nYou place the Rusty Battle Axe in the chest." << endl;
break;
case 'n':
case 'N':
inventory[0] = "Rusty Battle Axe";
cout << "\nYou leave the Short Sword in the chest." << endl;
break;
default:
cout << "\nThat was an invalid response!";
cout << "\nWould you like to trade the " << inventory[0] << " for the Short Sword? ";
continue;
}
break;
}
cout << "\nInventory:\n";
for(int i = 0; i < numItems; ++i)
{
cout << inventory[i] << endl;
}
return 0;
}