Home > OS >  C language- is there a function like isdigit() but can verify whether char contains double?
C language- is there a function like isdigit() but can verify whether char contains double?

Time:06-04

I am trying to verify whether my input has double number or not.

using isdigit() function can verify number 0~9 but can't verify double number such as 0.1, 0.5 or 0.771.

Is there another function? if not, how can I make this work?

CodePudding user response:

A char is only a single digit, but a string may contain several characters that can be interpreted as a double.

// Return 1 if a double found _somewhere_ in the string.
int verify_whether_string_contains_double(const char *s) {
  while (*s) {
    char *endptr;

    // Return the double (which we do not save)
    strtod(s, &endptr);
    // If `endptr1 the same as `s`, no conversion occurred.
  
    if (endptr > s) {
      return 1; // a portion of the string successfully converts to a double
    }
    s  ; // try again at the next char
  }
  return 0; // No part of the string contains a double.
}

Usage

char buf[100];
fgets(buf, sizeof buf, stdin);
if (verify_whether_string_contains_double(buf)) {
  puts("double found");
} else {
  puts("double not found");
}

If we want to detect if a string contains text that converted to a double and no extra junk:

int verify_whether_string_contains_only_double(const char *s) {
  char *endptr;

  strtod(s, &endptr);
  if (endptr == s) {
    return 0; // No conversion
  }

  // look for trailing junk
  // Let us allow trailing white-space.
  while (isspace(*(unsigned char*)endptr)) {
    endptr  ;
  }

  return *endptr == '\0';  // Success if we end at the string end.
}

CodePudding user response:

Here is a simple alternative to strtod() to check if a string contains the representation of a number:

#include <stdio.h>

// check if s contains a number with optional initial and trailing whitespace
int isnumber(const char *s) {
    double d;
    char c;
    return sscanf(s, "%lf %c", &d, &c) == 1;
}

CodePudding user response:

not perfect, but should do the job

int isfloat(const char* str, size_t len) {
  
  char c, dot = 0;
  
  for(size_t i = 0; i < len;   i) {
    
    c = str[i];
 
    if(!isdigit(c)) { 

      if(c == ' ' || c == '-')
        if(i != 0) return 0;

      if(c == '.') { 

        if(dot) 
          return 0;

        dot  ;

      } else {

        return 0;

      }
    }
  }

  return 1;
}
  •  Tags:  
  • c
  • Related