我有一个c功能:
void getInput(int turn)
{
int posI, posII, i, j;
char posC, c;
if(turn == 1)
{
c = 'B';
}
else if(turn == 2)
{
c = 'W';
}
int count = 0;
while(1)
{
printf("Enter the Cell:\n");
count++;
printf("I'm Here %d", count);
scanf("%c%d", &posC, &posI);
posII = (int)posC - (int)'A';
posI = posI - 1;
if(board[posII][posI] == '*')
{
board[posII][posI] = c;
for(i = 0 ; i < 8 ; i++)
for(j = 0 ; j < 8 ; j++)
{
if(board[i][j] == '*')
board[i][j] = ' ';
}
chageCell(posII, posI, c, 1, 0);
break;
}
else
{
printf("Wrong Cell\n try Again: \n");
}
}
}
这是黑白棋游戏的一部分,
问题是当我输入错误的单元格位置时,会出现消息 Wrong cell
在控制台中出现三次,但从逻辑上讲这是不可能的,每次显示 Wrong cell
后消息它应该等待第二次输入。
最佳答案
when I enter the wrong cell position, the message "Wrong cell" appears in console three times
根据输入的不同,“错误单元格”出现的次数与循环一次处理无效输入一个字符所需的次数一样多。
考虑:
scanf("%c%d", &posC, &posI);
当输入有效时,scanf
将读取一个字符和一个数字。当输入无效时,scanf
将仅读取一个字符,而将输入缓冲区中的其他所有内容留给 scanf
的后续调用。
您可以通过检查其返回值来判断 scanf
是否未读取 int
:
if (scanf("%c%d", &posC, &posI) != 2) {
// The input is incomplete. Ignore the input to end-of-line
...
continue;
}
// If the code reaches this line, you know that both `posC` and `posI` have been read correctly.
关于c - scanf() 不等待输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44870555/