Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

User Input check

Status
Not open for further replies.

emryoz

Programmer
Joined
Apr 1, 2002
Messages
4
Location
US
Hi,
I need a hint on how to make sure the user is entering a positive integer (no strings, no characters in between numbers, no negative numbers). The method I am trying to use is "atoi" conversion and the problem is it messes up when I try to enter zero although zero is an acceptable number. Here is my code;

int confirm, flag, down, up;
char number_of_entities[200], answer[100];

while(confirm)
{
printf("Input the number of entities> ");
scanf("%s", &number_of_entities);
printf("\n");
flag = 1;
while(flag)
{
down = (int)(floor(atof(number_of_entities)));
up = (int)(ceil(atof(number_of_entities)));

if(atoi(number_of_entities)>MAX_NUMBER || atoi(number_of_entities)<0)
{
printf(&quot;Please enter an appropriate number!!!\n&quot;);
scanf(&quot;%s&quot;, &number_of_entities);
}

else
{
if(up == down)
flag = 0;
else
{
printf(&quot;Please enter an appropriate number!!!\n&quot;);
scanf(&quot;%s&quot;, &number_of_entities);
}
}
}

printf(&quot;Number of entities you entered is> %d\n&quot;, atoi(number_of_entities));
printf(&quot;Is this correct?(y/n)\n&quot;);
scanf(&quot;%s&quot;, &answer);
if(answer[0] == 'y' || answer[0] == 'Y')
{
confirm = 0;
}
if(answer[0] == 'n' || answer[0] == 'N')
{
confirm = 1;
}
}

Thanx ;)
 
I didn't get any response yet. C'mon folks I know you can tackle this problem.
 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int verifyInt( char* s )
{
char c;
int i;

i=0;
if( s[0]=='0' && s[1]=='\0' )
return( 1 );
if( s[0]=='0' && s[1]!='\0' )
return( 0 );

while( 1 )
{
c=s[i++];
if( c=='\0' )
break;

if( !isdigit( c ) )
return( 0 );
}

return( 1 );
}

int main( void )
{
char sInput[20];

printf( &quot;Enter a positive int: &quot; );
fgets( sInput,sizeof( sInput ),stdin );
*( strrchr( sInput,'\n' ) )='\0';

if( !verifyInt( sInput ) )
printf( &quot;Please enter a valid positive int.\n&quot; );
else
printf( &quot;You entered: %d\n&quot;,atoi( sInput ) );

return( 0 );
} Mike L.G.
mlg400@linuxmail.org
 
Thank you very much Mike. It works great. I appreciate it.
 
Something like this should work (untested):

#include <errno.h>
#include <limits.h>
#include <stdlib.h>

/* Returns 1 if s can be converted
* to a positive integer, 0 otherwise */
int verify(const char *s,int base)
{
char *endptr
(void)strtoul(s,&endptr,base);
return errno!=ERANGE && !*endptr;
}
Russ
bobbitts@hotmail.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top