这主要是出于好奇,为什么会发生这种情况,因为在我的情况下并不重要。如果我键入一个无效的数字,它会正确地转到重复标签并要求我再次输入一个数字,但如果我输入一个像'f'这样的字符,它将无休止地循环而不会停止。为什么是这样?
这里的数组和所有变量都是int类型。
repeat:
printf("Enter number of available space, you are %c: ", userXO);
scanf("%d", user);
switch (*user)
{
case 1: if (spaces[0][0] == 49){ spaces[0][0] = userXO;}else goto repeat; break;
case 2: if (spaces[0][1] == 50){ spaces[0][1] = userXO;}else goto repeat; break;
case 3: if (spaces[0][2] == 51){ spaces[0][2] = userXO;}else goto repeat; break;
case 4: if (spaces[1][0] == 52){ spaces[1][0] = userXO;}else goto repeat; break;
case 5: if (spaces[1][1] == 53){ spaces[1][1] = userXO;}else goto repeat; break;
case 6: if (spaces[1][2] == 54){ spaces[1][2] = userXO;}else goto repeat; break;
case 7: if (spaces[2][0] == 55){ spaces[2][0] = userXO;}else goto repeat; break;
case 8: if (spaces[2][1] == 56){ spaces[2][1] = userXO;}else goto repeat; break;
case 9: if (spaces[2][2] == 57){ spaces[2][2] = userXO;}else goto repeat; break;
default: goto repeat; break;
}
答案 0 :(得分:5)
scanf("%d", user);
尝试读取一个数字,找到一个char(f
),将其留在缓冲区中并结束。循环然后循环并再次执行scanf("%d", user);
。再次......
答案 1 :(得分:2)
以下是我写下你所做的事情:
int rc, user;
char buf[100];
for (;;) // repeat until explicitly broken out of
{
printf ("Enter number of available space; you are %c: ", userXO);
if (!fgets (buf, sizeof buf, stdin)) /* end of file or i/o error? */
break;
rc = sscanf(buf, "%d", &user);
if (rc != 1) /* other than one parsed input item is an error */
{
printf ("invalid number; try again\n");
continue;
}
/*
* this switch has the odd property of potentially
* doing all 9 cases for case 1, 8 cases for case 2, etc.
* Maybe explicit breaks for success are needed?
*/
switch (user)
{
case 1: if (spaces[0][0] == 49) spaces[0][0] = userX0; else continue;
case 2: if (spaces[0][1] == 50) spaces[0][1] = userX0; else continue;
case 3: if (spaces[0][2] == 51) spaces[0][2] = userX0; else continue;
case 4: if (spaces[1][0] == 52) spaces[1][0] = userX0; else continue;
case 5: if (spaces[1][1] == 53) spaces[1][1] = userX0; else continue;
case 6: if (spaces[1][2] == 54) spaces[1][2] = userX0; else continue;
case 7: if (spaces[2][0] == 55) spaces[2][0] = userX0; else continue;
case 8: if (spaces[2][1] == 56) spaces[2][1] = userX0; else continue;
case 9: if (spaces[2][2] == 57) spaces[2][2] = userX0; else continue;
default: continue;
}
break; /* if valid case(s) taken, exits loop */
}
如您所见,不需要标签或转到。代码也更紧凑。