want user to input an integer value...the integer value is then converted to an ascii string....the ascii string is then passed into isValidNum(num); and it should return 1 if the number is valid and 0 if number is invalid.


for some reason it keeps returning 1 no matter what value i enter....any help would be greatly appreciated where i'm goofing up at! thx

int isValidNum( char str[] )
{
	int i = 0;
	int valid = TRUE;
	int sign = FALSE;

	if( str[0] == '\0' ) 
		valid = FALSE;

	if( str[0] == '-' || str[0] == '+' ) {
		sign = TRUE;
		i = 1;
	}

	if( sign == TRUE && str[1] == '\0' )
		valid = FALSE;

	while( valid == TRUE && str[i] != '\0' ) {
		if( str[i] < '0' || str[i] > '9' )
			valid = FALSE;
		i++;
	}

	return valid;
}

int main()
{
  int num = 33;
  char string[sizeof(int)+1] = {'\0','\0','\0','\0','\0'};

  itoa( num, string, 10 );
  printf("%d", isValidNum(string));
  
  return 0;
}

Edited 5 Years Ago by lochnessmonster: n/a

I would try simplifying your code...

#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>
#include <string.h>

bool isValidNum( char str[] )
{
	int i = 0;
	
	for (i = 0; i < strlen(str); ++i)
	{
		if (!isdigit(str[i]))
			return false;
	}

	return true;
}

int main()
{
	char string[] = {'\0','\0','\0','\0','\0'};

	printf("%d", isValidNum(string));

	return 0;
}

Edited 5 Years Ago by gerard4143: n/a

the main reason im not doing it like this is because the idnum must be atleast 5 digits long! your way is nice :) but wont quite work for my situation

the main reason im not doing it like this is because the idnum must be atleast 5 digits long! your way is nice :) but wont quite work for my situation

I really don't understand your concerns. If you have more information, please post it.

Edited 5 Years Ago by gerard4143: n/a

the number must be atleast 5 digits long!

now that i look at it i think thats where i messed up...tbh i have no idea how i would do this.

I fail to see how this won't work

#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>
#include <string.h>

bool isValidNum( char *str )
{
	int i = 0;
	
	for (i = 0; i < strlen(str) - 1; ++i)
	{
		if (!isdigit(str[i]))
			return false;
	}

	return true;
}

int main()
{
	char string[10];

	fputs("enter a number->", stdout);
	fgets(string, 10, stdin);

	printf("%d", isValidNum(string));

	return 0;
}

Edited 5 Years Ago by gerard4143: n/a

I could tell you how I would do it, but it smells like homework and something you should be working out on your own.

If you have specific problems, post complete, compilable code and ask specific questions.

If the number must be exactly 5 digits, you'd be better off reading the number as a string and passing it into your function. By reading an int, you have the possibility of an error on the read if they type in a non-digit character. Reading a string removes that possibility.

This article has been dead for over six months. Start a new discussion instead.