我想在 C 中创建一个函数,但不知道该怎么做 我知道如何使用整数而不是字符/字符串
printf("\nEnter player %d name: ", i);
scanf ("%s", playername[i]);
这让我可以读出名字。 %d 只是上面的一个数字
我想创建一个生成随机数的函数(我知道该怎么做)然后打印出问候消息
像这样
int grmessage;
grmessage = rand () %4;
srand (time(NULL));
if (grmessage == 0)
printf("Welcome to the game, %s!\n" , playername[i]);
else if (grmessage == 1)
printf("Hello %s and welcome!\n" , playername[i]);
else if (grmessage == 2)
printf("%s has joined us! Say hello!\n" , playername[i]);
else if (grmessage == 3)
printf("Pleasure to have you in this game %s!\n" , playername[i]);
else if (grmessage == 4)
printf("Why hello there %s!\n" , playername[i]);
else
printf("Say hello to %s who has entered the game.\n" , playername[i]);
现在有人可以告诉我如何将上面的代码块放入一个函数中
本质上是
...
void texter (char a) { my code above }
然后当我再次调用函数让它打印出文本时
printf("\nEnter player %d name: ", i);
scanf ("%s", playername[i]);
texter (playername[i]);
我知道我已经按字面意思给出了代码,但只需要修复它并使其正常工作,因为如果它是一个整数,我会这样做
最佳答案
只需使用一个字符数组来存储玩家的名字(正如您已经完成的那样)。像这样的事情:
char playername[no_of_players][100];
scanf ("%99s", playername[player_number]);
//NOTE: %99s to avoid overwriting the terminating '\0' character
并且您可以使用char*
数据类型将字符串作为参数发送给函数
texter()
函数原型(prototype):
void texter(char* name_sent)
{
//use name_sent to access the string sent into function
}
函数调用:
texter (playername[player_number]);
此外,只需在 main()
函数的开头使用一次 srand()
,不要在 texter
函数中使用它.看到这个:srand() — why call it only once?
关于C 中的字符函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40858359/