如何检查输入是否为字符

0 c input char

我正在学习c,正在制作一个“猜数字”游戏。我正在让玩家输入一个名字,我想检查它是否只是字符。

我想让这个非常简单的游戏变得更有趣,并为其添加更多的天赋(我计划做彩色文本等等。),

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>

int main() {
    // Initialize array for storing the playes name, players guess, counter for attempts to guess, a bool for the loop //
    // and  lowest and highest number for the random number generator. //
    char player_name[10];
    int player_guess;
    int count_tries = 0;
    
    bool run_game = false;
    
    int lower = 1, higher = 10;

    // Generate a ranom number //
    srand(time(NULL));
    int rand_num = rand() % (lower -higher) + 1;

    // Welcome message //
    printf("WELCOME TO THE GUESSING GAME\n");
    printf("Try to guess the secret number between 1 and 10\n\n");
    // printf("Rand number: %d\n\n", rand_num);
    
    // Get players name //
    printf("What is you name: ", player_name);
    scanf("%s", &player_name);
    }

    // Game Loop //
    do {
        printf("%s what you guess: (between 1 and 10)", player_name);
        scanf("%d", &player_guess);
        if (player_guess < rand_num) {
            printf("%s your guess waa too low!\n", player_name);
            count_tries++;
        }  
        if (player_guess > rand_num) {
            printf("%s your guess was too high!\n", player_name);
            count_tries++;
        }
        if (player_guess == rand_num) {
            printf("Congratulations %s you guessed the correct number!!!\n", player_name);
            count_tries++;
            printf("You guessed the correct number in %d attempts.\n", count_tries);
            break;
        }

    } while(run_game = true);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我尝试执行以下操作,但这也不起作用。

 if (player_name != char) {
        printf("Names can only be characters");
Run Code Online (Sandbox Code Playgroud)

Chr*_*ris 5

如果你想确定一个字符串是否只是字母字符,你需要一个函数来循环该字符串,一旦检测到非字母字符就短路并返回 false。

#include <ctype.h>
#include <stdbool.h>

bool only_alpha(const char *s) {
    for (; *s; s++) 
        if (!isalpha((unsigned char)*s))
            return false;

    return true;
}
Run Code Online (Sandbox Code Playgroud)

如果您希望它更灵活一点,您可以传递一个代表要在每个字符上运行的测试的函数指针。

bool string_only_contains(const char *s, int (*f)(int)) {
    for (; *s; s++) 
        if (!f((unsigned char)*s))
            return false;

    return true;
}

bool only_alpha(const char *s) {
    return string_only_contains(s, isalpha);
}
Run Code Online (Sandbox Code Playgroud)