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;
}

Dani AI

Generated

Quick troubleshooting, then a robust, practical check you can drop into main.

Common causes of “always returns true”

  • The buffer isn’t what you expect (not null-terminated, contains only what you converted with itoa, or is too small).
  • Boolean macros/types (TRUE/FALSE) or a missing prototype can hide logic bugs.
  • Trailing newline/whitespace or an overflow/partial-conversion case is not being detected.

As pointed out, treat the user input as a string. ’s character-by-character check is fine; below is an alternative that uses strtol to also detect overflow and trailing garbage, and enforces a minimum digit count (5). It trims a trailing newline, allows an optional sign, ensures every remaining character is a digit, verifies the minimum length, and finally uses strtol to detect range/partial-conversion errors.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

int is_valid_num_str(const char *s, size_t min_digits)
{
    if (!s || !*s) return 0;

    /* copy so we can safely strip trailing newline */
    char temp[64];
    size_t n = strlen(s);
    if (n >= sizeof temp) return 0; /* too long for this helper */
    memcpy(temp, s, n + 1);
    if (n && temp[n-1] == '\n') temp[n-1] = '\0';

    const char *p = temp;
    if (*p == '+' || *p == '-') ++p;
    if (!*p) return 0; /* only a sign */

    size_t digits = 0;
    for (const char *q = p; *q; ++q) {
        if (*q < '0' || *q > '9') return 0;
        ++digits;
    }
    if (digits < min_digits) return 0;

    errno = 0;
    char *end;
    (void)strtol(temp, &end, 10);
    if (errno == ERANGE) return 0;        /* overflow/underflow */
    return *end == '\0';
}

Practical tips

  • Replace any use of nonstandard itoa with snprintf/strtol as shown.
  • To debug the original problem: print the raw bytes of the buffer (as unsigned char values), and check that TRUE/FALSE are defined as you expect.
  • Pick a safe input buffer (e.g., 64 bytes), always strip newline from fgets, and test edge cases (empty string, “-”, “1234a”, very large numbers).

Recommended Answers

All 7 Replies

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;
}

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.

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;
}

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.