[ back to toc ]

do...while problem

Date: 2002/03/23 18:51

Dear Sir,

Below is my program. I want to know why the program can't restrict the
user inputting the letters if the equal sign removed in the while
statement as below:

while((num<0 || num >256));

However it is work if use while((num<=0 || num >=256));, but it make that
the user can't input 0. Can I have some hint of the solution.

Best Regards,


#include <stdio.h>
#include <stdlib.h>

main () {
int bits[8];
int num,k;

printf("Give a number(0-256):");
scanf("%d", &num);
if ((num<=0 || num >=256))
printf("Wrong number! Input again.\n");
}while((num<=0 || num >=256));

bits[k] = num %2;
num = num /2;

If the user enters letters and not digits then the function 'scanf'
results zero in the variable 'num'. How doy ou want to handle that? Your
code this way requires the user to type some number between 0 and 256
including the limits (why 256 by the way, didn't you mean 255?).

The function scanf is difficult to handle because it may not read the
terminatin new line. I recommend that you allocate a buffer, like

char buffer[80];

read a line using the function 'gets' and then use the function 'sscanf'
to get the number from the string.


[ back to toc ]