Alavi1412 Alavi1412 - 1 month ago 8
C Question

scanf() doesn't wait for input

I have a function:

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");
}
}
}


This is a part of Othello game,
the problem is when I enter the wrong cell position, the message
Wrong cell
appears in console three times but logically it is not possible, after each time showing the
Wrong cell
message it should wait for the second input.

Answer Source

when I enter the wrong cell position, the message "Wrong cell" appears in console three times

Depending on the input, "Wrong cell" will appear as many times as it takes the loop to work through the invalid input one character at a time.

Consider:

scanf("%c%d", &posC, &posI);

When the input is valid, scanf will read a character and a number. When the input is invalid, scanf will read only a character, leaving everything else in the input buffer to be consumed by subsequent calls of scanf.

You can tell if scanf didn't read the int by checking its return value:

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.