我正在学习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");
但这也不起作用。
我能做什么?
如果你想确定一个字符串是否只是字母字符,你需要一个函数来循环该字符串,一旦检测到非字母字符就短路并返回 false。
#include <ctype.h>
#include <stdbool.h>
bool only_alpha(char *s) {
for (; *s; s++)
if (!isalpha(*s))
return false;
return true;
}