提问人:Lacochina 提问时间:11/7/2023 最后编辑:ChrisLacochina 更新时间:11/7/2023 访问量:81
如何检查输入是否为 char
How to check if input is char or not
问:
我正在学习 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;
}
我尝试执行以下操作,但这也不起作用。
if (player_name != char) {
printf("Names can only be characters");
答:
5赞
Chris
11/7/2023
#1
如果要确定字符串是否只是字母字符,则需要一个函数,该函数循环该字符串,在检测到非字母字符时立即短路并返回 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;
}
如果希望它更灵活一些,可以传递一个函数指针,表示要对每个字符运行的测试。
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);
}
评论
0赞
Ted Lyngmo
11/7/2023
有趣。我没想到 C 会允许在 C23 标准中将库函数的地址与所有 s 一起获取,但是“即使它也被定义为宏,也允许采用库函数的地址。这意味着需要实现为每个库函数提供实际函数,即使它还为该函数提供了宏”。_Generic
0赞
Lacochina
11/10/2023
谢谢大家的帮助,现在工作正常。编辑:如何关闭线程?
评论
scanf()
==
!=
strcmp
char
char
'A'
char
int
run_game = true
run_game == true