我正在尝试验证数组的输入,以仅允许在数组的每个索引处输入一位整数(2 或 3)。例如 a = [2,3,2,3,2,2,2,2,2,3]
。我的尝试如下。
int main()
{
int a[10];
int b;
bool c= false;
printf( "Please the 10 values: \n");
while(c)
{
for(b=0;b<10;b++)
{
scanf("%d", &a[b]);//enter each value individually
if(&a[b]==2 || &a[b]==3)
{
c= true;
}
else
{
printf("please the value");
scanf("%d", &a[b]);
c= false;
}
}
}
}
最佳答案
如果你想检查值,你必须改变你的代码
if(&a[b]==2 || &a[b]==3)
到
if((a[b]==2) || (a[b]==3)) //no need for address of (&) operator
然而,对于像int a[10];
这样的数组,使用
for(b=0;b<32;b++)
将超出分配的内存,您将遇到未定义的行为。
也就是说,else
部分不检查重复输入的有效性。您也需要注意这一点。
此外,main()
的推荐签名是int main(void)
。
关于c - 验证数组的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29782944/