You really shouldn't use scanf
directly... especially if you're expecting multiple possible formats.
Consider using fread
instead and then converting the input to the proper format.
i.e.:
int main() {
while (1) {
char buf[1024];
printf("\nnumber to convert:\n ");
unsigned long len = fread(buf, 1, 1023, stdin);
buf[len] = 0;
if (len == 0 || (len == 1 && buf[0] == '\n') ||
(len == 2 && buf[0] == '\r' && buf[1] == '\n'))
break;
int val = atoi(buf);
ibits(val);
}
return 0;
}
This will also allow you to validate input and test for overflow attacks:
int main() {
while (1) {
char buf[1024];
printf("\nnumber to convert:\n ");
unsigned long len = fread(buf, 1, 1023, stdin);
buf[len] = 0;
if (len > 11)
goto under_attack;
if (len == 0 || (len == 1 && buf[0] == '\n') ||
(len == 2 && buf[0] == '\r' && buf[1] == '\n'))
break;
if (buf[0] != '-' && (buf[0] < '0' || buf[0] > '9'))
goto under_attack;
int val = atoi(buf);
ibits(val);
}
return 0;
under_attack:
fprintf(stderr, "Under attack?!\n");
return -1;
}