我又在做作业了,我的作业是与土耳其城市的刽子手游戏。 代码还没有完成,因为有一个有趣的问题。 当我用 MSYS2 编译器运行代码时,我的输出应该是这样的:
_______ //the random cities letter numbers determines how many "_" in here
Sehri tahmin et! // "Guess the city!"
Bir harf soyle //pls tell me a letter
b //user input
Tahmin ettigin harf: b // the letter u guessed
_ _ _ _ _ //?
Bir harf soyle //pls tell me a letter
u //user input
Tahmin ettigin harf: u // the letter u guessed
_ _ _ _ _ //?
Bir harf soyle //pls tell me a letter
a //user input
Tahmin ettigin harf: a // the letter u guessed
a _ _ _ _ //user input
Bir harf soyle //pls tell me a letter
但它看起来像这样:
_ _ _ _ _
Sehri tahmin et!// "Guess the city!"
Bir harf soyle //pls tell me a letter
b //user input
Tahmin ettigin harf: b // the letter u guessed
♥ _ _ _ _ //?
Bir harf soyle //pls tell me a letter
u //user input
Tahmin ettigin harf: u // the letter u guessed
♥ _ _ _ _ //?
Bir harf soyle //pls tell me a letter
a //user input
Tahmin ettigin harf: a // the letter u guessed
a _ _ _ _ //user input
Bir harf soyle //pls tell me a letter
有一颗心出现,直到我猜对了第一个字母
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct correctGuess{
int letterNumber;
char letter;
};
int main() {
srand(time(NULL));
char cities[][10] = { "antalya","ankara","istanbul","izmir","kutahya","bursa","konya","afyon","balikesir","mugla" };
char guessedLetter[30];
struct correctGuess correctGuess[10];
char indexLetter;
int i = 0, guessCounter = 0;
int letter = 0;
int random = (int)(rand() % 10);
while (cities[random][i] != '\0') {
letter++;
i++;
correctGuess[i].letterNumber = i;
correctGuess[i].letter = '\0';
}
for (int i = 0; i < letter; i++) {
printf("_ ");
if (i == (letter - 1)) {
printf("\n");
}
}
printf("Sehri tahmin et!\n"); //en: "Guess the city!"
for (;;) {
printf("Bir harf soyle\n"); //en: "pls tell me a letter"
scanf(" %c", &indexLetter);
while (getchar() != '\n');
printf("Tahmin ettigin harf: %c\n", indexLetter); //en: "The letter u guessed
guessCounter++;
guessedLetter[guessCounter] = indexLetter;
int correctGuessIndex = 0;
for (int i = 0; i < letter; i++)
{
if(cities[random][i] == indexLetter){
correctGuess[correctGuessIndex].letter = indexLetter;
correctGuess[correctGuessIndex].letterNumber = i;
}
correctGuessIndex++;
}
for(int i = 0; i < letter; i++){
if(correctGuess[i].letter == '\0'){
printf("_ "); //the problem probably here!!
}else{
printf("%c ",correctGuess[i].letter);
}
if(i == (letter - 1)){
printf("\n");
}
}
}
return 0;
}
所以我的问题只在我使用 msys2 编译器时出现,但是当我使用像 this 这样的在线编译器时它工作正常。我该如何解决?为什么会这样?
这个“心”字大概是个控制字。 ASCII控制字符做一些控制,但也可以按字面意思显示; ♥ 是其中之一,代码为 3.
注意显示的不是下划线
_
。代码打印correctGuess[i].letter
。所以你可以合理地确定在代码的那个地方,它有这个奇怪的值 3.
为什么它在那里有那个价值?它未初始化;它可以有任何价值。未初始化的变量通常值为 0;这看起来好像您的代码正常工作。