Complete.Org: Mailing Lists: Archives: discussion: February 2000:
[aclug-L] Re: C question
Home

[aclug-L] Re: C question

[Top] [All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index] [Thread Index]
To: discussion@xxxxxxxxx
Subject: [aclug-L] Re: C question
From: Tom Hull <thull@xxxxxxxxxxx>
Date: Tue, 29 Feb 2000 21:16:01 -0600
Reply-to: discussion@xxxxxxxxx

Sure, you can use scanf() with "%n" ... if you're a glutton for punishment.
There are easier ways.

strtol, strtoul, strtod convert strings to numbers (long, unsigned long,
double), and all take an optional pointer-to-pointer argument, which if
non-zero is set to the first non-numeric character.

for instance, if s is a null-terminated string:

  #include <ctype.h>
  #include <stdlib.h>
  #include <stdio.h>

  void print_numbers(const char *s)
  {
    char *p;
    while (*s) {
      if (isdigit(*s)) {
        printf("%lu\n", strtoul(s, 10, &p));
        s = p;
      }
      else
        s++;
    }
  }

OTOH, I'd probably write this function w/o the subroutine, since strtoul()
will botch numeric strings > ULONG_MAX. The following only prints out the
all-digit substrings:

  void another_print_numbers(const char *s)
  {
    while (*s) {
      if (isdigit(*s)) {
        do {
          putchar(*s++)
        } while (isdigit(*s));
        putchar('\n');
      }
      else
        s++;
    }
  }

I don't know jack about perl, but you could also filter a whole file through
the following command to get the same effect:

  tr -cs '[0-9]' '\012' | grep '[0-9]'

or, equivalently:

  tr -cs '[0-9]' '\012' | grep -v '^$'

Note that tr always/only reads from stdin.    

Larry Bottorff wrote:
> 
> Let's say I have a buffer full of characters and I want to separate out
> the characters from numbers where consecutive numbers represent a single
> integer. For example: "HELLO OUT THERE 234 I AM NUMBER 8". The 234 and
> the 8 need to be picked out of the array and converted to integer and
> stored as integers. sscanf might work, but then I need to tell the
> buffer index to advance how ever many places the integer takes up in
> order to continue. Building a character array, then convert that string
> to integer seems reasonable, but I can't find a library function for it.
> Any ideas?
> 
> Lars
> 
> -- This is the discussion@xxxxxxxxx list.  To unsubscribe,
> visit http://tmp2.complete.org/cgi-bin/listargate-aclug.cgi

-- 
/*
 *  Tom Hull * thull@xxxxxxxxxxx * http://www.ocston.org/~thull/
 */

-- This is the discussion@xxxxxxxxx list.  To unsubscribe,
visit http://tmp2.complete.org/cgi-bin/listargate-aclug.cgi


[Prev in Thread] Current Thread [Next in Thread]