Re: how can we check to not enter the any string or char?
- From: "Charlie Gordon" <news@xxxxxxxxxxx>
- Date: Tue, 6 Nov 2007 19:41:40 +0100
"pete" <pfiland@xxxxxxxxxxxxxx> a écrit dans le message de news:
472917DC.425A@xxxxxxxxxxxxxxxxx
emre esirik(hacettepe computer science and engineering) wrote:
int n_mines;
printf("How many mines do you want in the minefield?");
scanf("%d", &n_mines);
while(n_mines>100 || n_mines<0)
{
printf("Please only enter between 1 and 100");
scanf("%d", &n_mines);
}
so I dont want to user can enter the string or char value,
how can I check it?
/* BEGIN n_mines.c */
/*
** Bulletproof numeric input with fscanf.
*/
#include <stdio.h>
#include <stdlib.h>
#define LENGTH 4
#define str(x) # x
#define xstr(x) str(x)
int main(void)
{
int rc;
char array[LENGTH + 1];
long number;
int n_mines;
for (;;) {
printf("How many mines do you want in the minefield?: ");
fflush(stdout);
rc = fscanf(stdin, "%" xstr(LENGTH) "[^\n]%*[^\n]", array);
if (!feof(stdin)) {
getc(stdin);
}
if (rc == 0 || rc == EOF) {
array[0] = '\0';
number = 0;
} else {
number = strtol(array, NULL, 10);
}
if (number > 100 || number < 1) {
printf("Please only enter between 1 and 100\n");
} else {
n_mines = number;
printf("\nn_mines is %d.\n", n_mines);
break;
}
}
return 0;
}
/* END n_mines.c */
This program does not let me type 000001 as a response to the question :-(
--
Chqrlie.
.
- Follow-Ups:
- References:
- Prev by Date: Re: Looking for quality source code to read
- Next by Date: Re: how can we check to not enter the any string or char?
- Previous by thread: Re: how can we check to not enter the any string or char?
- Next by thread: Re: how can we check to not enter the any string or char?
- Index(es):
Relevant Pages
|