'Richard Cavell' richardcavell@mail.com [c-prog]
7 years ago
Hi everyone.
Â
For my program (which is in C89, no external libraries allowed) I need to accept a command line argument and convert it to an unsigned numeric value. The lowest possible value is always 0. The highest possible value is a parameter to the function. I want to accept as many valid inputs as possible, and detect all possible errors. For the purpose of my project, I want a number with a leading $ sign to be interpreted as hexadecimal.
Â
This is the best that I've been able to come up with, with my present level of skill. Is there any error that I am not detecting, or feature that is easily added that I have not added?
Â
static unsigned long int
string_to_unsigned_long(const char     *pstring,
            boolean_type    *ok,
            unsigned long int  max)
{
  unsigned long int l = 0;
  char *endptr = NULL;
  int base = 0;
Â
  errno = 0;
Â
  if (pstring != NULL)
    while (*pstring == ' ')
      ++pstring;
Â
  if (pstring != NULL && pstring[0] == '$')
  {
    base = 16;
    ++pstring;
  }
  else
    base = 0;
Â
  if (pstring != NULL)
    l = strtoul(pstring, &endptr, base);
Â
  *ok = (   pstring   != NULL
      && *pstring   != '\0'
      &&  endptr   != NULL
      && *endptr   == '\0'
      &&  errno    == 0
      &&  pstring[0] != '-'
      &&  l <= max );
Â
  return l;
}
Â
Â
For my program (which is in C89, no external libraries allowed) I need to accept a command line argument and convert it to an unsigned numeric value. The lowest possible value is always 0. The highest possible value is a parameter to the function. I want to accept as many valid inputs as possible, and detect all possible errors. For the purpose of my project, I want a number with a leading $ sign to be interpreted as hexadecimal.
Â
This is the best that I've been able to come up with, with my present level of skill. Is there any error that I am not detecting, or feature that is easily added that I have not added?
Â
static unsigned long int
string_to_unsigned_long(const char     *pstring,
            boolean_type    *ok,
            unsigned long int  max)
{
  unsigned long int l = 0;
  char *endptr = NULL;
  int base = 0;
Â
  errno = 0;
Â
  if (pstring != NULL)
    while (*pstring == ' ')
      ++pstring;
Â
  if (pstring != NULL && pstring[0] == '$')
  {
    base = 16;
    ++pstring;
  }
  else
    base = 0;
Â
  if (pstring != NULL)
    l = strtoul(pstring, &endptr, base);
Â
  *ok = (   pstring   != NULL
      && *pstring   != '\0'
      &&  endptr   != NULL
      && *endptr   == '\0'
      &&  errno    == 0
      &&  pstring[0] != '-'
      &&  l <= max );
Â
  return l;
}
Â