【发布时间】:2017-11-08 13:50:39
【问题描述】:
我正在尝试向我在 for 循环中定义的数组添加一个字母。对于用户每次输入内容,我想将“counterSoFar”减 1,并显示它。但是,“counterSoFar”总是减少 2 并跳过用户输入任何内容的机会,而不是将“counterSoFar”减少 1。我尝试多次查看代码,但我仍然无法弄清楚为什么。请指教。
# include <stdio.h>
# include <ctype.h>
void userInput(char[]);
int main() {
printf("Player 1 please enter a word of up to 12 letters.\n");
char word[13];
scanf("%13s", word);
userInput(word);
}
void userInput(char word[])
{
int n = strlen(word);
for (int i = 0; i < n; i++)
{
word[i] = tolower(word[i]);
}
int checker;
for (int i = 0; i < n; i++)
{
if (isalpha(word[i]))
{
checker = 1;
}
else
{
checker = 0;
printf("Please enter a word without spaces and numbers!\n");
break;
}
}
if (checker == 1)
{
int counterSoFar = 8;
char letter[1];
printf("The word to guess is as follows: \n");
for (int i = 0; i < n; i++)
{
printf("_");
}
int maxTries = 7;
for (int guessCounter = 0; guessCounter < maxTries; guessCounter++)
{
printf("\n");
counterSoFar = counterSoFar - 1;
printf("You have %d tries left!\n\n", counterSoFar);
printf("Player 2 please enter only 1 letter!\n");
scanf("%c", &letter);
char array[13];
for (int c = 0; c < n; c++)
{
if (letter == word[c])
{
array[c] = word[c];
}
else
{
array[c] = '_';
}
}
printf("The current array is %c", array);
}
}
}
【问题讨论】:
-
-scanf("%c",&letter);
-
双倍递减是由 stdin 中的尾随换行符引起的。请阅读stackoverflow.com/questions/35178520/…
-
它不负责你问的问题,但是要打印数组
array,你必须使用%s字段描述符(不是%c,它是针对单个字符的),并且您必须确保该数组包含一个字符串终止符。 -
另外,我建议避免冗余。当
maxTries和guessCounter(一起)已经携带相同的信息时,为什么要创建和管理变量counterSoFar。也就是说,我建议不要使用printf("You have %d tries left!\n\n", counterSoFar);,而是完全放弃counterSoFar并使用printf("You have %d tries left!\n\n", maxTries - guessCounter);。
标签: c arrays loops for-loop counter