好的..所以我有那个代码,我不能让Do While声明正确...
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int nWinsPC, nWinsPlayer;
char cChoose[1];
do {
system("cls");
printf("Vamos jogar um jogo?\n");
printf("-\n");
printf("Escolha (p)edra, p(a)pel ou (t)esoura: ");
getchar();
scanf("%1[^\n]", cChoose);
} while(cChoose != "p");
system("pause");
}
那个系统应该那么容易......选择屏幕会保持循环,而播放器不输入“p”,但我无法正常工作......
:(
提前致谢
修改
问题解决了:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
int nWinsPC, nWinsPlayer;
char cChoose[2];
do {
system("cls");
printf("Vamos jogar um jogo?\n");
printf("-\n");
printf("Escolha (p)edra, p(a)pel ou (t)esoura: ");
scanf("%s", cChoose);
} while ( strcmp(cChoose,"p") );
system("pause");
}
答案 0 :(得分:3)
int cChoose;
...
cChoose = getchar();
} while( cChoose != 'p' && cChoose != EOF );
您似乎喜欢使用scanf,可能是因为它为您处理空白。相反,尝试:
int cChoose;
...
do cChoose = getchar(); while( isspace( cChoose ));
} while( cChoose != 'p' && cChoose != EOF );
(虽然这是写一个奇怪的方式,但实际上只是使用do / while的另一个例子。通常会写:
int cChoose;
...
while( isspace( cChoose = getchar()))
;
} while( cChoose != 'p' && cChoose != EOF );
答案 1 :(得分:1)
用于比较C中两个字符串的方法是strcmp
,如
while ( strcmp( cChoose, "p" ) )
strcmp
如果字符串相同则返回0(false),如果它们不同则返回非零值。
您的陈述
while ( cChoose != "p" )
比较内存中两个指针的位置,其中一个指针cChoose
指向堆栈上的数据,"p"
指向静态数据。他们永远不会平等。
答案 2 :(得分:0)
你应该使用 strcmp 而不是“!= ”检查cChoose的内容是否等于“p”。
cChoose是一个指向内存中数组起始位置的指针。它绝对不等于内存中的“p”起始位置,因此您可以在程序中获得无限循环。
答案 3 :(得分:0)
声明:
strcmp ( cChoose, "p" )
必须使用,如果两个字符串相等则返回零。 此外,如果您使用cChoose作为字符串,则必须使用两个字符作为cChoose的长度,因为字符串始终以空字符 - '\ 0'终止。所以,使用:
char cChoose[2];
编辑:
scanf()之前的getchar()接受初始'p',因此第一次没有任何事情发生。而第二次,getchar()首先接收第一行中的'\ n'并且scanf正确读取“p”。 删除getchar(),你的代码就可以了。