我写了下面的函数:
typedef enum {GREEN,BLACK, WHITE} color;
void StartGame(Piece board[8][8])
{
color currentPlayer=WHITE;
char location[2];
int gameover=1;
while(gameover)
{
printf("%d\n",currentPlayer);
if(currentPlayer==WHITE)
printf(BOLDWHITE"White: Please select a piece:\n");
else
printf(BOLDBLACK"Black: Please select a piece:\n");
printf("%d\n",currentPlayer);
scanf("%s",location);
printf("%d\n",currentPlayer);
if(currentPlayer==WHITE)
currentPlayer=BLACK;
else
currentPlayer=WHITE;
}
}
我在任何级别上打印 currentPlayer
以查看发生了什么 -> 这里是我得到的:
2
White: Please select a piece:
2
a1
0
2
White: Please select a piece:
2
为什么scanf
后当前播放器为0?我没有碰它。
最佳答案
缓冲区 location
只有 2 个字符的空间,scanf
在末尾放置了一个额外的 NUL 字符。因此,您遇到了堆栈损坏问题。只需给 location
留出更多空间,例如:
char location[8];
编辑
因为你只想读取一个字符串,我推荐你使用fgets
,它允许您限制从输入字符串中读取的字符数。因此,我的代码将如下所示:
char location[8];
...
fgets(location, sizeof(location), stdin); //instead of scanf, fgets reads at most one less than buffer's size characters.
您只需要担心 fgets
将最后一个结束行字符 (\n
) 放在末尾这一事实,但如果您只需处理字符串的前 2 个字符。
关于c - scanf 后变量重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25249738/