www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - std.string.atoi: requires cast?

reply "Lynn Allan" <l_d_allan adelphia.net> writes:
<alert comment="newbie">

I was wondering why the compiler rejected lines 6 and 7. The documentation
doesn't mention anything about:
intC atoi(char*)

#import std.string;
#void main ()
#{
#  char[4] numStr1 = "1234";
#  long num1 = atoi(numStr1);          // <-- Ouch
#  num1 = std.string.atoi(numStr1);   // <-- Ouch
#  num1 = atoi(cast(char[])numStr1);

#  char[] numStr2 = "4321";
#  long num2 = atoi(numStr2);
#  num2 = std.string.atoi(numStr2);
#}
// .\Test.d(6): function atoi overloads intC (char*) and long(char[]s) both
match argument list for atoi
// .\Test.d(7): function atoi overloads intC (char*) and long(char[]s) both
match argument list for atoi

</alert>
Sep 25 2004
parent Ben Hinkle <bhinkle4 juno.com> writes:
Lynn Allan wrote:

 <alert comment="newbie">
 
 I was wondering why the compiler rejected lines 6 and 7. The documentation
 doesn't mention anything about:
 intC atoi(char*)
 
 #import std.string;
 #void main ()
 #{
 #  char[4] numStr1 = "1234";
 #  long num1 = atoi(numStr1);          // <-- Ouch
 #  num1 = std.string.atoi(numStr1);   // <-- Ouch
 #  num1 = atoi(cast(char[])numStr1);
 
 #  char[] numStr2 = "4321";
 #  long num2 = atoi(numStr2);
 #  num2 = std.string.atoi(numStr2);
 #}
 // .\Test.d(6): function atoi overloads intC (char*) and long(char[]s)
 both match argument list for atoi
 // .\Test.d(7): function atoi overloads intC (char*) and long(char[]s)
 both match argument list for atoi
 
 </alert>

icky. The std.string module's atoi(char[] s) just calls atoi(toStringz(numStr1)) so probably the simplest thing to do is call long num1 = atoi(toStringz(numStr1)); (don't worry about the toStringz allocating a new string because the literal "1234" has a trailing 0) or as you suggest just go ahead and tell the compiler which atoi by casting. It is unfortunate that the D atoi overloads the C atoi. Maybe all those C functions should be private and add some std.c.string or something. -Ben
Sep 25 2004