Reputation: 13
That's my code so far:
int main(void) {
int byte[8], position = 0, match8 = 0;
printf("Please enter 1 byte as a binary sequence: ");
match8 = scanf("%1d%1d%1d%1d%1d%1d%1d%1d", &byte[0], &byte[1], &byte[2], &byte[3], &byte[4], &byte[5], &byte[6],&byte[7]);
return 0;
}
Now I want to make sure that the user made a correct input and if not the program should say "Error! Please enter 1 byte as a binary sequence: "
and check the input again.
I tried:
while(getchar() != '\n' || match8 != 8) {
...do something
}
But I can't figure out how to check if the array contains only 0 and 1.
I hope you can help me with my problem :)
Upvotes: 0
Views: 86
Reputation: 153348
Suggest to avoid scanf()
and use fgets()
to read a line of user input
char buf[100];
if (fgets(buf, sizeof buf, stdin)) {
Then use strspn()
to test buf[]
for only '0'
or '1'
size_t strspn(const char *s1, const char *s2);
Thestrspn
function computes the length of the maximum initial segment of the string pointed to bys1
which consists entirely of characters from the string pointed to bys2
. C11 7.23.5.6
size_t offset = strspn(buf, "01");
if (buf[offset] == '\n') {
buf[offset--] = '\0'; // eat trailing \n
}
if (offset == 8 && buf[offset] == '\0') {
sscanf(buf, "%1d%1d%1d%1d%1d%1d%1d%1d",
&byte[0], &byte[1], &byte[2], &byte[3], &byte[4], &byte[5], &byte[6],&byte[7]);
// Success!
}
}
Upvotes: 0
Reputation: 40145
try this
char bits[9], ch;
int byte[8];
while(1){
printf("Please enter 1 byte as a binary sequence: ");fflush(stdout);
bits[8] = 1, ch = 0;
if(2 == scanf(" %8[01]%c", bits, &ch) && ch == '\n' && bits[8] == 0)
break;
if(ch != '\n')
while(getchar() != '\n');//clear input
printf("Error! ");
}
sscanf(bits, "%1d%1d%1d%1d%1d%1d%1d%1d", &byte[0], &byte[1], &byte[2], &byte[3], &byte[4], &byte[5], &byte[6],&byte[7]);
Upvotes: 3
Reputation: 2498
A scanset %8[01]
could be used to restrict input to the characters 0 and 1. The 8 will also limit input to 8 characters. The characters can be converted to numbers with number = onezero[i] - '0';
#include <stdio.h>
#include <string.h>
int main( void) {
char onezero[9] = "";
int valid = 0;
do {
printf("Please enter 1 byte as a binary sequence: ");
if ( ( 1 == ( valid = scanf ( " %8[01]", onezero))) && ( 8 == strlen ( onezero))) {
printf ( "input was %s\n", onezero);
}
else {
if ( valid == EOF) {
break;
}
while ( getchar ( ) != '\n') {}
valid = 0;
}
} while ( !valid);
return 0;
}
Upvotes: 1
Reputation: 768
try this...
int main(void) {
int byte[8]={0};
printf("Please enter 1 byte as a binary sequence: ");
for(int i=0; i<8; i++)
{
byte[i]=getchar()-'0';
if(byte[i]!=0&&byte[i]!=1) /*error*/;
}
return 0;
}
Upvotes: -1