提问人:oskarw7 提问时间:10/19/2023 更新时间:10/19/2023 访问量:87
如何阻止循环结束得太快?
How to stop the loop from ending too quickly?
问:
我的任务是创建一个游戏,其中四个玩家 G1-G4 正在掷骰子。首先,用户必须写入名为 X 的板长度(没有文件 0)。然后他分别为每个玩家写 1-6 的 M 加号。如果他想打印当前结果,他会写 P。当某人拥有 X 或更多时,他就赢了。我不能使用字符串。 我在这里有一个 while 循环问题。每次我尝试在输入中放置 M+smth 时,游戏都会在第一次迭代后结束。 queue 用于管理玩家掷骰子的次数(因为按 P 会导致迭代中断)
#include <iostream>
using namespace std;
int main(){
unsigned int X, queue=0, g1=0, g2=0, g3=0, g4=0;
char input[3];
cin >> X;
while(g1<X && g2<X && g3<X && g4<X){
cin >> input;
if(input[0]=='P'){
cout << g1 << " " << g2 << " " << g3 << " " << g4 << endl;
continue;
} else{
queue++;
switch(queue%4){
case 1: g1=g1+(input[2]-'0');
case 2: g2=g2+(input[2]-'0');
case 3: g3=g3+(input[2]-'0');
case 0: g4=g4+(input[2]-'0');
}
}
}
cout << "END OF GAME";
return 0;
}
我尝试在每个“案例”之后添加中断指令,将 switch 语句更改为 if/if else 并用 getchar() 替换输入。但是,以上方法都没有奏效。我还将 C 样式的 char 数组更改为字符串,但它给出了相同的结果。
答:
您的代码似乎存在一些问题,涉及语法和内存。另外,尽量不要添加这个非常常提到的问题中列出的原因。using namespace std;
首先,对于内存,您需要小心使用 C 样式的字符串。你看,当你想要一个字符串时,比如说,n个字符,那么你实际上需要建立一个带有另一个内存字符的char数组,以便编译器可以将该字符添加到它的末尾。如果您想了解更多细节,请对此进行一些研究,但在处理 C 样式字符串时,请记住这一点。因此,只需将数组声明为大小为 4。'\0'
input
其次,您发布的代码显示您在切换语句后没有添加任何关键字。你看,它的工作方式是,一旦它找到一个匹配的大小写,它就会在那之后执行行,直到它击中一个关键字或。如果它点击中断,它将退出开关。但是,如果它命中,它将继续执行您在它下面输入的行。break
switch
break
case
case
例如,使用您的代码,如果等于 2,则将输入值添加到 、 和 中。因此,如果您只想递增一个值,则需要在每种情况下都有一个。queue%4
g2
g3
g4
break
之后,我测试了我刚刚编辑的代码,并得到了正确的结果。您可以在此处获取带有输入的演示:
7
M+2
M+4
M+6
M+3
P
M+5
带有编辑和注释的新代码:
#include <iostream>
int main (){
unsigned int X, queue=0, g1=0, g2=0, g3=0, g4=0;
char input[4]; //Just simple change from 3 to 4 here to stop memory issues and correct the last character so it is your number, not some garbage value or forced '\0' character that could make the value you add (input[2] - '0') incorrect
std::cin >> X;
while(g1<X && g2<X && g3<X && g4<X){
std::cin >> input;
if(input[0]=='P'){
std::cout << g1 << " " << g2 << " " << g3 << " " << g4 << '\n';
continue;
} else{
queue++;
switch(queue%4){
case 1: g1=g1+(input[2]-'0'); break; // 4 breaks to stop other adding, that could potentially already make other values go over K
case 2: g2=g2+(input[2]-'0'); break;
case 3: g3=g3+(input[2]-'0'); break;
case 0: g4=g4+(input[2]-'0'); break;
}
}
}
std::cout << "END OF GAME";
return 0;
}
首先,尽量不要添加:
使用命名空间 std;
另外,你在内存方面也有一些问题,因为你必须知道在数组的末尾存在一个 ,使用**'\0'**
std::cin;
你必须添加语句,因为你只想一次增加一个值,并且在编写 imput 之后,你添加不杀死程序。break;
continue;
评论
continue;
下一个:C++ 循环融合似乎没有发生
评论
cin >> input;
'M'
,加上三个,没有空间' '
'1'
char
'\0'
input[3]
不适合 - 没有空间用于终止 NUL 字符。如果是用户键入的内容,则程序会通过缓冲区溢出的方式表现出未定义的行为。P 6
P 6