trim 0s

N

Netocrat

(e-mail address removed) wrote:
Zara wrote:
pemo wrote:
Can anyone suggest a nice way to trim any leading zeros off of a
string, e.g., I'd like to take a string like 00000012 and convert
it to 12.

char *s_ini="00000012";
char *s_final=s_ini;
while (*s_final=='0') s_final++;

Almost ... oh what the hell, might as well do it right:

for (i = 0; s_ini == '0'; i++) if (s_ini == '\0' && i > 0) {
i--;
break;
}

s_final = &s_ini;
[...]
I suspect you are going to say that you think "0000" with leading zeroes
removed is "0", and you also planned to write a program that gives "0",
but you accidentally wrote a program that gives "".


If so it's easily fixed and the result isn't obscure:

for (i = 0; s_ini == '0'; i++) ;
if (s_ini == '\0' && i > 0)
i--;
s_final = &s_ini;

The specification isn't clear enough to decide on correctness, but this
seems like more useful semantics when dealing solely with numeric strings
that must later be displayed as integers.
 
W

websnarf

S.Tobias said:
Who said anything about numbers? The OP only wanted to remove
all initial zeroes from a string. :)
http://dspace.dial.pipex.com/town/green/gfd34/art/bloopers.html
"This is a lovely picture ..." is very adequate here.

Seriously, I'm sure the OP has already discovered by now
what he really needed.

If you think that sort of bug tends to eventually get sorted out in
serious applications try the following:

printf ("%f\n", 0);

.... in Microsoft Visual Studio 2003. This is the result I got:

86191978822782173000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000

I wish I were kidding (it prints out other numbers just fine).
 
W

websnarf

If you think that sort of bug tends to eventually get sorted out in
serious applications try the following:

printf ("%f\n", 0);

... in Microsoft Visual Studio 2003. This is the result I got:

86191978822782173000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000

I wish I were kidding (it prints out other numbers just fine).

Nevermind ... I just caught what I did wrong.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,169
Messages
2,570,920
Members
47,462
Latest member
ChanaLipsc

Latest Threads

Top