Originally Posted by
jarvis
pls help me, i am making a do while loop which wont accept invalid inputs..
these invalid inputs include outside the range of 1-100, negative numbers, and zero, also i would like my loop not to accept floats, negative floats, strings and characters..
is that possibel? i dont have an idea how to do the latter part, involving not accepting floats ang strings and character..
here's what i've gotten to so far
Code:
/* gets the user's bet */
do
{ printf ("Your bet: $ ");
scanf ("%d", &nBet);
}
while (nBet < 1 || nBet > 100);
printf ("\n");
thanx!
Your best bet would be to steer clear of the scanf function altogether. Its usage can cause problems, and since there are other nice solutions which don't involve using scanf, why not try some of them?
It seems that there are many ways of getting a number from a user, and validating it. Have a look at the relevant FAQ, and you will see what I mean. There are more methods even than what are demonstrated in the FAQ. My personal favourite is to use fgets to read in a line of text, and then convert it to whatever format of number using sscanf.
Code:
#include <stdio.h>
static int get_num(int arg_num, int *err_var);
static void need_num(void);
int main(void)
{
int bet = 0;
int getnum_fail = 0;
/* Get the user's bet */
do {
printf("Your bet: $ ");
fflush(stdout);
bet = get_num(1, &getnum_fail);
if (getnum_fail == -1) { /* call to get_num failed */
need_num();
getnum_fail = 0;
}
} while (bet < 1 || bet > 100);
return 0;
}
static int get_num(int arg_num, int *err_var)
{
enum {
BUF_SIZE = 100
};
int test = 0;
char buffer[BUF_SIZE] = { (char) 0 };
int value = 0;
if ((fgets(buffer, BUF_SIZE, stdin)) != NULL) {
test = sscanf(buffer, "%d", &value);
}
if (test != arg_num) { /* sscanf was a failure */
*err_var = -1;
}
return value;
}
void need_num(void)
{
(void) puts("\nEnter the values in numeric format please.\n");
}
Basically I put the call to get_num in a loop and pass it two values. One is the 'magic number' 1 - this number is used in the function to see if sscanf got one conversion. If it did, then we can return that converted number. If it did not, then we set the variable getnum_fail via the pointer we passed in. Then we try again until success.
I would explain more, but my wife is waiting on me to go out
For some more very nice examples of getting numbers from the user, check out Dave Sinkula's article on the matter.