gpt4 book ai didi

c - 对不同的数组使用指针?

转载 作者:行者123 更新时间:2023-11-30 19:45:33 25 4
gpt4 key购买 nike

我无法弄清楚如何让此 Hangman 程序根据用户输入选择要使用的正确数组。虽然我意识到我可以轻松设置包含相同代码的不同 if 语句,但这似乎是不必要的内存使用量。所以我的问题是:我可以使用指针(或者最好是更简单的东西)来表示数组名称,这样我只需要一个代码序列吗?我尝试通过指针来完成此操作,但我相信我弄错了,所以如果有人有任何提示,我将不胜感激。

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


int main(){

char easy_animals[2][3] = {
{ 'c', 'a', 't' }, //0
{ 'd', 'o', 'g' }, //1
};

char easy_names[2][3] = {
{ 'p', 'a', 't' }, //0
{ 'b', 'o', 'b' }, //1
};

char u,
newline,
dis[16] = { '_', '_', '_', '_' };
input[10];

int random,
guesses = 3,
finish = 0;

_Bool successfulGuess = false;

srand(time(NULL));
random = rand() % 13;

printf("Animals or names?\n");
gets(input);

if (input[0] == 'a'){ // Or any other letter to signify the correct subject

printf("Animal %d\n", random); // Check random number
printf("---------\n\n");

while (guesses > 0){
finish = 0;
successfulGuess = false;
printf("Enter a letter: ");
u = getchar();
newline = getchar();

for (int i = 0; i < 3; i++){

if (u == dis[i]){
successfulGuess = true;
printf("\nYou already guessed this letter.\n");
printf("\ninput = dis[i]\nGuesses left: %d\n\n", guesses);
break;
}
else if (easy_animals[random][i] == u){
successfulGuess = true;
dis[i] = u;
printf("\ninput = array char\nGuesses left: %d\n\n", guesses);
}
}
printf("\n");

for (int i = 0; i < 3; i++){
printf("%c", dis[i]);
}

if (successfulGuess == false){
guesses--;
printf("\n\nbool statement\nGuesses left: %d\n\n", guesses);
}

if (guesses == 0){
printf("Sorry, you've run out of guesses.");
}

for (int i = 0; i < 3; i++) {
if (dis[i] != '_') {
finish++;
}
if (finish == 3){
printf("\n\nYou guessed the word!");
guesses = 0;
}
else{
continue;
}
}
printf("\n\n");
}

}
system("pause");
}

最佳答案

easy_animalseasy_names 都是指向 char 的指针数组。选择用户必须猜测的单词只意味着选择这些指针之一,因此请声明自己一个可用于表示该单词的 char*:

char* wordToGuess;

然后将其分配给从相关数组中随机选择的指针,如下所示:

if (/*user selects "animals"*/)
{
wordToGuess = easy_animals[random];
}
else if (/*user selects "names"*/)
{
wordToGuess = easy_names[random];
}
else (/*input is invalid*/)
{
// Prompt the user to re-enter his/her choice.
}

最后,在确定用户是否成功猜测时使用新指针:

else if (wordToGuess[i] == u){
successfulGuess = 1;
dis[i] = u;
printf("\ninput = array char\nGuesses left: %d\n\n", guesses);
}

关于c - 对不同的数组使用指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26186804/

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