我想创建一个随机化字符串的游戏,用户必须猜测原始字符串是什么,但是当我显示随机字符串时,它会被打印两次。一次随机一次不随机化。这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int checkWin(char guess[], char word[]);
void jumble(char array[]);
int main()
{
srand(time(NULL));
char word[5] = {'h', 'e', 'l', 'l', 'o'};
char scramble[5] = {'h', 'e', 'l', 'l', 'o'};
char guess[5];
jumble(scramble);
printf("The jumled word is: %s\n",scramble);
printf("Enter a guess: ");
for(int i = 0; i < 5; i ++)
{
scanf(" %c",&guess[i]);
}
printf("\n");
if(checkWin(guess,word))
printf("You win!");
else
printf("You lose");
}
void jumble(char array[])
{
int a,b,c;
for(a = 1; a<6; a++)
{
b = rand()%5;
c = rand() %5;
if(b==c)
{
a--;
continue;
}
char temp = array[b];
array[b] = array[c];
array[c] = temp;
}
}
int checkWin(char guess[], char word[])
{
int a = 0;
for(int i = 0; i < 5; i ++)
{
if(guess[i] == word[i])
a++;
}
if(a==5)
return 1;
else
return 0;
}
当用户猜到字符串时它工作正常但是当我尝试显示乱码字符串时,我会得到类似的内容:
The jumled word is: ollehhello"
Enter a guess: hello
You win!
Process returned 0 (0x0) execution time : 9.645 s
Press any key to continue.
我不知道字符串出了什么问题,所以任何帮助都会受到赞赏。
答案 0 :(得分:6)
您的字符串不会NUL
终止,因此%s
格式代码正在通过它们运行(如果不需要对齐填充,堆栈变量通常背靠背布局,尽管这是直到它最终找到巧合的NUL
字节(在另一个编译器上,它可能会打印出更多的乱码或崩溃)。
要修复,请使用字符串文字(隐式添加\0
),手动添加\0
,或者将它们调整为比初始化大一个(额外元素隐式为零),例如:
// Not declaring sizes; the arrays size based on the literal to size 6
char word[] = "hello";
char scramble[] = "hello";
或
// Again, autosizing to 6
char word[] = {'h', 'e', 'l', 'l', 'o', '\0'};
char scramble[] = {'h', 'e', 'l', 'l', 'o', '\0'};
或
// Explicit sizing to 6, implicit initialization of uninitialized element to 0
char word[6] = {'h', 'e', 'l', 'l', 'o'};
char scramble[6] = {'h', 'e', 'l', 'l', 'o'};