好的..。所以我有那个代码,我不能正确地理解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");
}
发布于 2012-10-08 10:04:32
声明:
strcmp ( cChoose, "p" )
必须使用,如果两个字符串相等,则返回零。此外,如果使用cChoose作为字符串,则必须使用两个字符作为cChoose的长度,因为字符串总是以空字符“\0”结尾。因此,请使用:
char cChoose[2];
编辑:
scanf()之前的getchar()接受初始的'p',因此第一次什么都不会发生。而第二次,getchar()第一次接收第一行中左边的'\n‘并正确地读取"p“。如果删除getchar(),您的代码就会正常工作。
发布于 2012-10-08 09:09:17
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 );
发布于 2012-10-08 09:09:18
您应该使用的比较C中两个字符串的方法是strcmp
,如
while ( strcmp( cChoose, "p" ) )
如果字符串相同,strcmp
返回0 (false),如果字符串不同,则返回非零值。
你的陈述
while ( cChoose != "p" )
比较内存中两个指针的位置,其中一个是cChoose
指向堆栈上的数据,另一个是指向静态数据的"p"
。他们永远不会平等。
https://stackoverflow.com/questions/12786266
复制相似问题