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

时间:2018-01-16 21:15:59

标签: 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, 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;
}   

1 个答案:

答案 0 :(得分:1)

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

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