gpt4 book ai didi

c - 获取用户输入的第一个字符,丢弃 c 中的其余字符

转载 作者:太空宇宙 更新时间:2023-11-03 23:40:05 26 4
gpt4 key购买 nike

在我目前的代码中,如果用户输入的字符串不是以 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;
}

最佳答案

您可以清除 printf 之前 else block 开头的输入。

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

关于c - 获取用户输入的第一个字符,丢弃 c 中的其余字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48289963/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com