FIREHIVE FIREHIVE - 1 year ago 69
C Question

Keyboard input of array of bits

I want to make a program that applies some logic gates (

) to elements of two arrays of 1 and 0. But I am having problems with the user input of these arrays. I don't know how to make the arrays store only 1 and 0, for example if I type 5 I want the program to tell me it's neither 0 nor 1 and start over, I tried something but it's not working:

int v1[50],v2[50],i,j,n;
printf("Number of elements in arrays : ");

printf("Introduce elements of first array :\n");

if(v1[i] == 0 || v1[i]==1)
else (i'll make it a function and I want it to repeat if the elements given are not 1 and 0)


Answer Source

Suppose you have an array consisting of 50 elements:

int v1[50];

If you want to fill it with values only of 0 and 1 you should set up a while loop, until the user puts in correct data:

int iter, result;
for (iter = 0; iter < 50; iter++)
    while ((result = scanf("%d", &v1[iter])) != 1  // no number was found
            || (v1[iter] != 0 && v1[iter] != 1))   // OR it was and it wasn't 0 or 1
        if (result != 1)
            scanf("%*s");  // case 1: dispose of bad input
            printf("Please, use only values 0 or 1\n");  // case 2: remind the user
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download