Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to determine if a string contains a period

Tags:

c

I'm trying to determine if a string contains a certain symbol, specifically a period. I'm using this to determine if a number is a real number or an integer. The first condition is that the string has to contain a number between 0 and 9 to be considered a number, then if it has a period (decimal) it will be considered a real number. If no period, then it is an integer. I can't figure out what I'm doing wrong, thanks in advance!

void typenumber(char *str)
{
  int i=0;

  if(str[i]>='0' && str[i]<='9')
  {
    if(str[i]=='.')
    {    
       printf("String %s is a real number.\n", str);
    }
    else
    {
        printf("String %s is an integer.\n", str);
    }
  }
  return;
}
like image 403
austin Avatar asked Oct 19 '25 01:10

austin


1 Answers

I'm trying to determine if a string contains a certain symbol, specifically a period.

This you can check using strchr(), like this:

if (strchr(str, '.') != NULL) {
   printf("String %s is a real number.\n", str);
}
else {
    printf("String %s is an integer.\n", str);
}

But there is a possibility that your input string may contain multiple '.' character or a character other than digits and period character. So, it is better to loop through the each and every character of the input string and check it, like this:

#define INT_NUM  1
#define REAL_NUM 2

int typenumber(char *str) {
        int num_type = INT_NUM;

        if ((str == NULL) || (*str == '\0')) {
                printf ("Invalid input\n");
                return 0;
        }

        while (*str != '\0') {
                if (!isdigit(*str)) {
                        if ((*str == '.') && (num_type == INT_NUM)) {
                                num_type = REAL_NUM;
                        } else {
                                return -1;
                        }
                }
                str++;
        }

        return num_type;
}
like image 79
H.S. Avatar answered Oct 21 '25 15:10

H.S.