-3

这主要是出于好奇为什么会发生这种情况,因为在我的情况下并不重要。如果我输入一个无效的数字,它会正确地转到重复标签并要求我再次输入一个数字,但如果我输入一个像“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;
}
4

2 回答 2

5

scanf("%d", user);尝试读取一个数字,找到一个 char( f),将其留在缓冲区中并结束。然后循环循环并scanf("%d", user);再次执行。然后再次...

于 2013-04-21T01:21:34.883 回答
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 */
}

如您所见,不需要标签或 goto。代码也更紧凑。

于 2013-04-21T01:56:44.887 回答