在c语言中,取用户输入的第一个字符,丢弃其余字符

在c语言中,取用户输入的第一个字符,丢弃其余字符,c,C,在我当前的代码中,如果用户输入的字符串不是以c或s开头,它将检查字符串中的每个字符,并继续输出printf。如何使它只检查第一个字符,并允许用户键入新字符串进行检查 #include <stdio.h> #include <math.h> #include <stdlib.h> #include <string.h> int main() { //Declare Variables int players, P1, P2, P3, P4, loop

在我当前的代码中,如果用户输入的字符串不是以c或s开头,它将检查字符串中的每个字符,并继续输出printf。如何使它只检查第一个字符,并允许用户键入新字符串进行检查

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
int main()
{
//Declare Variables
int players, P1, P2, P3, P4, loop, loop2;
char gameType;
char c;
//Initialize Variables
players = 0;
P1 = 0;
P2 = 0;
P3 = 0;
P4 = 0;
loop = 1;
loop2 = 1;

//Figure out what game type
printf("Commander or Standard?\n"); 
gameType = getchar();
    while (loop == 1)
    {   
        if (gameType == 'C' || gameType == 'c')
        {
            P1 = 40, P2 = 40, P3 = 40, P4 = 40;
            loop = 0;   
            printf("How many players?\n");
            scanf("%s", &players);
            printf("%c players\n", players);
        }
        else if (gameType == 'S' || gameType == 's')
        {
            P1 = 20, P2 = 20;
            printf("Player 1 HP: %d\n", P1);        
            printf("Player 2 HP: %d\n", P2);
            loop = 0;                   
        }
        else 
        {
            printf("Please enter either Commander or Standard\n");
            loop = 1;
            gameType = getchar();
        }
    }

return 0;
}   
#包括
#包括
#包括
#包括
int main()
{
//声明变量
int播放器,P1,P2,P3,P4,loop,loop2;
配子类型;
字符c;
//初始化变量
玩家=0;
P1=0;
P2=0;
P3=0;
P4=0;
循环=1;
环2=1;
//找出游戏类型
printf(“指挥官还是标准?\n”);
gameType=getchar();
while(循环==1)
{   
如果(游戏类型='C'| |游戏类型='C')
{
P1=40,P2=40,P3=40,P4=40;
循环=0;
printf(“有多少玩家?\n”);
scanf(“%s”和玩家);
printf(“%c players\n”,players);
}
else if(游戏类型=='S'| |游戏类型=='S')
{
P1=20,P2=20;
printf(“玩家1生命:%d\n”,P1);
printf(“玩家2生命:%d\n”,P2);
循环=0;
}
其他的
{
printf(“请输入Commander或Standard\n”);
循环=1;
gameType=getchar();
}
}
返回0;
}   

您可以在printf之前清除else块开头的输入

while ( (gameType = getchar()) != '\n' && gameType != EOF ) { }

fgets
,然后取第一个字符…Oops-
scanf(“%s”,&players)但您有
int players
,需要
%d
格式规范。请不要更正回复评论时发布的代码。回滚。除了验证输入的值外,还必须检查所有用户输入的函数返回值。
getchar
是否返回
EOF
(旁白:
char gameType;
应该是
int gameType;
)?
scanf
是否返回您期望的成功输入数?您还有
printf(“%c players\n”,players)和-错误的格式说明符。