Re: how can we check to not enter the any string or char?



In <1193862410.106448.76840@xxxxxxxxxxxxxxxxxxxxxxxxxxxx> "emre esirik(hacettepe computer science and engineering)" <emreesirik@xxxxxxxxx> writes:

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?

Read the input as a string first. Examine the string to see if it contains
any incorrect characters. If it does not, convert the string to its
decimal value.

string input[80];
int n_mines;
int i;
int good_input = 1;

printf("How many mines do you want in the minefield?");
fgets(input, sizeof(input), stdin);

for(i = 0; i < strlen(input); i++)
{
if(isalpha(input[i]))
{
// whoops! user entered a character
good_input = 0;
break;
}
}

if(good_input == 1)
{
n_mines = atoi(input);
}
else
{
printf("You must enter a number.\n");
}

--
John Gordon A is for Amy, who fell down the stairs
gordon@xxxxxxxxx B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"

.



Relevant Pages