所以我试着用基本的C ++编写一个简单的基本游戏,当我尝试执行这个时
// global variabless
const char UP = 'w', LEFT = 'a', DOWN = 's', RIGHT = 'd'; // player movement choices
char playerMove; // goes with askPlayer
void askPlayer()
{
char choice;
cout << "Use the WASD keys to move: ";
cin >> choice;
int worked;
do{
if (choice == 'w' || choice == 'W')
{
playerMove = UP;
worked = 1;
}
else if (choice == 'a' || choice == 'A')
{
playerMove = LEFT;
worked = 1;
}
else if (playerMove == 's' || playerMove == 'S')
{
playerMove = DOWN;
worked = 1;
}
else if (playerMove == 'd' || playerMove == 'D')
{
playerMove = RIGHT;
worked = 1;
}
else
{
cout << "Invalid entry." << endl;
worked = 0;
}
} while (worked != 1);
return;
}
这取决于输入信件的用户。 Xcode说(lldb)然后页面填满了数字,在你停止运行之后,它说&#34;程序结束时退出代码:9&#34;。即使您输入其中一个有效值
,它也会这样做答案 0 :(得分:3)
用户输入第一个值后,您永远不会提示其他值:
cin >> choice; // <==
int worked;
do {
// ..
} while (worked != 1);
只需将输入移动到循环中:
int worked;
do {
cin >> choice; // possibly with cout prompt too
// rest as before
} while (worked != 1);
答案 1 :(得分:0)
您的输入不在循环中,您的变量worked
未初始化(虽然它不是代码中的错误,但初始化变量更简洁)并且它应该具有bool
类型。整个代码可以通过switch
语句简化:
void askPlayer()
{
do {
char choice;
cout << "Use the WASD keys to move: ";
cin >> choice;
switch( choice ) {
case 'w' : case 'W' :
playerMove = UP;
break;
case 'a' : case 'A' :
playerMove = LEFT;
break;
case 's' : case 'S' :
playerMove = DOWN;
break;
case 'd' : case 'D' :
playerMove = RIGHT;
break;
default:
cout << "Invalid entry." << endl;
continue;
}
} while( false );
return;
}