Code:
void checknumber(char string[])
{
int i;
for (i=0; string[i] != '\0'; i++)
{
if(string[0] == '\0' || string[i] < 45 || string[i] == 47 || string[i] > 57)
{
exit(1);
}
if(i>0 && string[i] == 45)
{
exit(1);
}
}
}
And this function is useful...how?
Code:
main()
{
char string[10];
float num;
do
{
printf("Enter number : ");
gets(string);
checknumber(string);
num = atof(string);
}
getchar();
}
That sure is a lot of errors for one little function. main returns an int, anything else and you'll be sorry. Identifiers starting with str are reserved, gets should never be used, num is a float and atof returns a double, a do..while loop should actually have the while part included or it won't work, and checknumber does nothing except quit the program. How useless is that?
How about something more along the lines of this:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
/* Just fooling around, int works fine too */
enum ISVAL { VALID, INVALID };
typedef enum ISVAL val_t;
static val_t checknumber ( char *astr )
{
while ( *astr != '\0' )
if ( !isdigit ( *astr++ ) )
return INVALID;
return VALID;
}
int main(void)
{
char astr[10];
if ( fgets ( astr, 10, stdin ) != NULL ) {
if ( astr[strlen(astr)-1] == '\n' )
astr[strlen(astr)-1] = '\0';
if ( checknumber ( astr ) == INVALID )
printf ( "Invalid integer\n" );
else
printf ( "Your number is %d\n", atoi ( astr ) );
}
return 0;
}
-Prelude