LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   how to check and remove leading zeroes from the buffer using c program (https://www.linuxquestions.org/questions/programming-9/how-to-check-and-remove-leading-zeroes-from-the-buffer-using-c-program-682622/)

amit_pansuria 11-11-2008 09:43 AM

how to check and remove leading zeroes from the buffer using c program
 
Helo ,
I m writing small module of c.on RHEL 4

I have one buffer (for e.g. buffer = "002"
now I want to check whethere buffer contains leading zeroes and if it contains
leading zeroes then I want to remove all leading zeroes
( i.e. if buffer = "002" then I want to make buffer = "2")

how do I do using c code

Regards,
Amit

tronayne 11-11-2008 10:04 AM

Easy way? Try using strtol() and sprintf(), something like this
Code:

int    value;

/*    get what's in buf as a number    */
value = (int) strtol (buf, (char **) NULL, 10);
/*    copy it back    */
(void) sprintf (buf, "%d", value);

You can also do that all in one whack; replace "value" in the sprintf with the strtol.

You can also use the atoi() function (the strtol() function is more complicated):
Code:

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

main    ()
{
        char    buf [BUFSIZ];

        (void) sprintf (buf, "002");
        (void) fprintf (stdout, "%d\n", atoi (buf));
}


dwhitney67 11-11-2008 04:32 PM

Another option, is to use strtok().
PHP Code:

  // check if leading zero exists
  
if (buf[0] == '0')
  {
    
// remove leading zero(es)
    
sprintf(buf"%s"strtok(buf"0"));
  } 


Sergei Steshenko 11-11-2008 04:39 PM

Quote:

Originally Posted by dwhitney67 (Post 3338758)
Another option, is to use strtok().
PHP Code:

  // check if leading zero exists
  
if (buf[0] == '0')
  {
    
// remove leading zero(es)
    
sprintf(buf"%s"strtok(buf"0"));
  } 


Well, probably doesn't matter in this case, but 'sprintf' is slow compared to memmove + strlen.

estabroo 11-11-2008 05:31 PM

or something really simple

Code:

        char    buf [BUFSIZ];
        char*  p = buf;
        char*  e = buf+BUFSIZ;
...
        while ((p < e) && (*p == '0') {
          p++;
        }
...
}



All times are GMT -5. The time now is 04:09 PM.