[ back to toc ]

do...while problem

Date: 2002/03/25 09:41

Q:
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 >255));

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

Best Regards,

*NAME-DELETED*

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

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

do{
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));

for(k=0;k<8;k++){
bits[k] = num %2;
num = num /2;
};
for(k=7;k>=0;k--){
printf("%d",bits[k]);
};
printf("\t");
}

A:
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.

regards,
Peter
Q:
Dear Peter,

Thanks for your help, but the code I gave you yesterday is not the
original one. The correct one is as below, sorry for that.

Actually, I found that gets() is not help in this situation, would you
mind helping me again?

Thank you very much!

Best regards,

*NAME-DELETED*

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

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

do{
printf("\nGive a number(0-255):");
gets(input);
num=atoi(input);
if (num<=0 || num >=255)
printf("\nWrong number! Input again.");
}while(num<=0 || num >=255);

for(k=0;k<8;k++){
bits[k] = num %2;
num = num /2;
};
for(k=7;k>=0;k--){
printf("%d",bits[k]);
};
printf("\t");
}

A:
Insert a line

do{
printf("\nGive a number(0-255):");
gets(input);
num=atoi(input);

printf("%s %d\n",input,num);// inserted line

if (num<=0 || num >=255)
printf("\nWrong number! Input again.");
}while(num<=0 || num >=255);

and see what the program does.

Also I do not get the point why you exclude the zero or 255 as values. Why
do not you write

}while(num<0 || num >255);

Maybe I am missing the problem you have.

Regards,
Peter

[ back to toc ]