Reputation: 123
So what I'm thinking about doing is a little program where the user inputs a binary number (i.e 1010010100111000001), and then it is stored in an array, where each array position is associated with a digit of my number. Example: bit[0] = 1, bit[1] = 0 etc. The code I have in mind is this but i don't believe it works:
int bit [31];
scanf("%i", bit);
Help please!
Upvotes: 0
Views: 66
Reputation: 7996
The main problem is how to ensure the user enters a valid binary number, i.e. exclusively 0s and 1s. You can try to read the inputs character by character and check the input is valid by using the standard sscanf format: %[01]
. You should also limit the size of the input to a single character. Hence the final format: %1[01]
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]) {
int bits[31];
char input[2];
int i;
int j;
fprintf(stdout, "Enter at most 31 bits: ");
for(i=0; i<31 && 1 == fscanf(stdin, "%1[01]", input); ++i)
bits[i] = (input[0]=='1' ? 1 : 0);
fprintf(stdout, "You entered: \n");
for(j=0; j<i; ++j)
fputc(bits[j]?'1':'0', stdout);
fprintf(stdout, "\n");
return 0;
}
Upvotes: 1
Reputation: 40145
#include <stdio.h>
int main(void) {
char line[64];
int bit[32];
int i, n;
scanf("%32[01]", line);//fgets(line, sizeof(line), stdin);//input up to newline
for(i = 0; i < 32; ++i){
if(1!=sscanf(&line[i], "%1d", &bit[i]))//read one digit
break;
}
n = i;
for(i = 0; i < n; ++i){
printf("%d", bit[i]);
}
putchar('\n');
return 0;
}
Upvotes: 0
Reputation: 134286
Without the error check, the code you need is
char bitstream[31];
scanf("%30s", bitstream);
Upvotes: 0