Re: how can we check to not enter the any string or char?
- From: santosh <santosh.k83@xxxxxxxxx>
- Date: Thu, 01 Nov 2007 02:31:53 +0530
John Gordon wrote:
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];
What is this 'string' type? It's not defined in Standard C and if it is
C++'s std::string you might prefer to post in comp.lang.c++.
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");
}
What about input like 23.3 or 34&%$3 and other combinations?
I suggest using isdigit instead of isalpha. Also cast the is* function's
arguments to unsigned char.
Also check fgets for success, otherwise input's contents will be
indeterminate. strtol might also be a better alternative to atoi
providing status reporting.
.
- Follow-Ups:
- Re: how can we check to not enter the any string or char?
- From: John Gordon
- Re: how can we check to not enter the any string or char?
- References:
- how can we check to not enter the any string or char?
- From: emre esirik(hacettepe computer science and engineering)
- Re: how can we check to not enter the any string or char?
- From: John Gordon
- how can we check to not enter the any string or char?
- Prev by Date: Re: how can we check to not enter the any string or char?
- 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
|