c - 如何在C中标记要选择的字符
问题描述
到目前为止,这是我的刽子手游戏代码。我有几个问题,其中一些是如何将选定的字母标记为“SELECTED”,因此当用户选择另一个字母时,不能使用他已经使用过的字母。而且,我有一个失败的条件,如果满足,游戏应该以一条消息中断,但它永远不会中断。
我已经尝试创建另一个数组,我将在其中推送所有已选择的字符。但是,它不起作用,因为我遇到了错误,因为我不能将字符放在随机位置,因为以前的插槽不会被填充。
这是我的主要方法:
int main() {
srand(time(NULL));
// the randomly selected word
char *word = generateStrings();
char sampleArray[strlen(word)];
sampleArray[strlen(word)] = '\0';
for (int i = 0; i < strlen(word); i++) {
sampleArray[i] = '_';
}
printf("%s\n", word);
char *printedWord = printWord(sampleArray, word);
return 0;
}
这是基本上完成所有逻辑的方法:
char *printWord(char sampleArray[], char *word) {
char letter;
int stopLoop=0;
int x = 0;
int winningSpree = 0;
int lost = 0;
while (1) {
system("@cls||clear"); // clear cmd window every itereation of the loop
printf("%s\n", word);
if (winningSpree==strlen(word)) {
printf("Congratulations! You've won!\n");
printf("%s", sampleArray);
break;
}
if (lost == 6) {
printf("You lost!\n");
printf("The word was: ", word, "\n");
break;
}
if (x == 0)
for (int i = 0; i < strlen(word); i++)
printf("_");
if (x > 0)
printf("Current stage of word: %s", sampleArray);
printf("\n");
printf("Give me a letter: ");
letter = askforinput();
printf("\n");
for (int j = 0; j < strlen(word); j++) {
if (word[j] == letter) {
sampleArray[j] = letter;
winningSpree++;
} else {
lost ++;
}
}
x++;
}
printf("\n");
return sampleArray;
}
这是要求输入的方法:
// ask user for character input
char askforinput() {
char chosenLetter;
scanf("%c", &chosenLetter);
return chosenLetter;
}
解决方案
要将所选字母标记为“SELECTED”,您可以实现以下代码:-
int count=0; //for keeping track of how many letters the user has selected.
int maxnumberofinputs=10;//for maximum number of times user can guess.
char selected[maxnumberofinputs]; //the selected letters will go here.
char letter=askforinput();
//when user selects a letter
if(count<maxnumberofinputs)
{
selected[count]=letter;
count++;
}
推荐阅读
- jquery - 允许 HTML 表格尽可能宽
- amazon-web-services - 从ALB切换到NLB后健康检查失败?
- node.js - 如何在 hapi.js 中实现 Joi 验证?
- javascript - 在Javascript中区分2个字符串
- java - @ServiceActivator 如何在 Spring Boot 中从属性文件中读取 inputChannel?
- elasticsearch - ElasticSearchRepository deleteBy 在单元测试中不起作用
- javascript - NodeJS 从多个 http 请求中获取数据
- c# - 解决任务。扩展当前行并获得价值
- pandas - 将特定行从一列移到下一列
- azure-active-directory - Microsoft Graph API beta/reports 没有数据