我试图弄清楚如何确保用户输入正确的字符。基本上,我希望用户输入c或u。到目前为止,它可以正常工作,直到用户输入以u或c开头的词组为止。我希望他们只按c或u,而字母上没有任何其他字符。我认为这与有关数组的事情有关,但是我对数组没有太多的了解。在这里:
#include <stdio.h>
int main()
{
char turn;
printf("Welcome to the game of Sticks. The objective is to pick up the last stick\n\n");
printf("Please choose who goes first. (u for user and c for computer): ");
scanf(" %c", &turn);
while (turn != 'c' && turn != 'u') //Checking if user inputted c or u
{
printf("\nPlease enter u to go first or c for computer to go first!\n");
scanf(" %c", &turn);
}
return 0;
}
答案 0 :(得分:0)
绝对不要使用==
比较运算符来比较字符串...
请改为使用strncmp
中定义的"string.h"
函数
例如,
#include <stdio.h>
#include <string.h>
int main(void){
char turn[] = "";
scanf("%c",&turn);
while(strncmp(turn,'c',sizeof('c')) != 0) && (strncmp(turn,'u',sizeof('u')) != 0){
//If User didn't enter c or u
scanf("%c",&turn);
}
return 0;
}
哦,还要始终确保初始化在函数中定义的变量,例如,通过执行类似turn
的操作来初始化char turn = "";
变量。
这是为了防止在内存地址中为turn
变量分配一个随机值。