2

我正在创建一个程序,它应该验证我输入的正确值,但不幸的是我做错了。如果答案是 1 或 0,该程序需要检查输入值 10 次。否则它必须再次要求答案。输入完成后,它应该通过 printf 显示正确答案,但事实并非如此。

我的猜测是“开关盒”部分出了点问题。帮助将不胜感激!

我的代码:

int main()

{
char a0, a1, a2, a3, a4, a5, a6, a7, a8, a9;
char c = '0';
int a = 0, OK = 0, check = 0, valid_input = 0, a_ok;

printf("Fill in a value 1 or 0.\n\n");

while (a < 10)
{
while (valid_input == 0)
{
    printf("Fill in a%d: ", a);
    a_ok = scanf("%d", &OK);
    if (a_ok != 1)
    {
        scanf("%s", &c);
    }
    else if (OK <0 | OK >1)
    {
        do
        {
            while (check == 0)
            {
            printf("Fill in a%d: ", a);
            check = check +1;
            }
        c = getchar();
        }
        while (!isdigit(c));
        ungetc(c, stdin);
    }
    else
    valid_input = 1;
}
switch (a)
    {
    case 0:
    OK = a0;
    case 1:
    OK = a1;
    case 2:
    OK = a2;
    case 3:
    OK = a3;
    case 4:
    OK = a4;
    case 5:
    OK = a5;
    case 6:
    OK = a6;
    case 7:
    OK = a7;
    case 8:
    OK = a8;
    case 9:
    OK = a9;
    }
a = a +1;
}

/*
printf("Fill in a1: ");      **<--- WANT TO REMOVE THIS PART BY LOOP**
scanf("%d", &a1);
printf("\nFill in a2: ");
scanf("%d", &a2);
printf("\nFill in a3: ");
scanf("%d", &a3);
printf("Fill in a4: ");
scanf("%d", &a4);
printf("\nFill in a5: ");
scanf("%d", &a5);
printf("Fill in a6: ");
scanf("%d", &a6);
printf("\nFill in a7: ");
scanf("%d", &a7);
printf("\nFill in a8: ");
scanf("%d", &a8);
printf("Fill in a9: ");
scanf("%d", &a9);
*/

printf("\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d", a0,a1,a2,a3,a4,a5,a6,a7,a8,a9);

getch();
return(0);
}
4

1 回答 1

7

您忘记了break开关的每种情况下的声明:

case 0:
    OK = a0;
    break;
case 1:
    OK = a1;
    break;
/* etc. */

另外,这个if说法是错误的:

if (OK <0 | OK >1)

您可能打算使用||逻辑 OR 运算符,而不是|按位 OR 运算符。

此外,您的 aN 变量(a0, a1, ... a9)未在任何地方初始化。它们的初始值是未定义的。

另外(我这里的续词用完了:-P),这个:

while (!isdigit(c));

只是看起来不对。这相当于:

while (!isdigit(c))
{
}

这意味着它是一个无限循环 whenisdigit(c) == 0并且什么也不做 when isdigit(c) != 0。也许你打算写这个:

while (!isdigit(c)) {
    ungetc(c, stdin);
}

但即便如此,您仍会stdin在无限循环中将同一个角色推回原处。

这也是错误的:

scanf("%s", &c);

c是一个char变量,但你告诉 scanf() 读取一个字符串。

不是错误,而是应该使用数组而不是 10 个单独的变量:

char val[10];

所以,而不是:

a0 a1 ... a9

你将拥有:

val[0] val[1] ... val[9]

Anyway, this program is extremely broken. If you just began to learn C, I'd recommend starting from scratch and paying more attention.

于 2012-11-22T13:07:51.083 回答