itoa'd you so?

Weston Cerny weston at aircomusa.com
Wed Sep 19 15:24:31 MDT 2007


Weston Cerny wrote:
>
>
> Levi Pearson wrote:
>> Steve <smorrey at gmail.com> writes:
>>  
>>> I came up with 2 solutions which both amounted to roughly the same 
>>> code.
>>>
>>> std::string itoa(int in){
>>>     std::stringstream out;
>>>     out << in;
>>>     return(out.str());
>>> }
>>>
>>> and
>>>
>>> char* itoa(int in){
>>>     std::stringstream out;
>>>     out << in;
>>>     return(out.rdbuf.c_str());
>>> }
>>>
>>> So my question is, what is wrong with this method (I haven't tested it
>>> so there may be a minor syntax error, but that aside)?
>>>     
>>
>> What's wrong with that method is that it's using the standard library,
>> which was explicitly not available.  C++ kind of hides the fact that
>> you're essentially calling itoa() when you do out << in there, once
>> you go through the overloaded function that implements <<, etc.
>>
>> So, try doing it again in plain C without using any standard library
>> functions.
>>
>>                 --Levi
>>
>> /*
>> PLUG: http://plug.org, #utah on irc.freenode.net
>> Unsubscribe: http://plug.org/mailman/options/plug
>> Don't fear the penguin.
>> */
>>
>>
>>
>>   
>
> What about and I am not a C or C++ person so i'll avoid the char* 
> discussion and just use string to denote the operations?
> string itoa(int in) {
>    string ret = "";
>    int current = in;
>
>    while (current > 0 && current %= 10)
>    {
>       ret = (char)((int)current + (int)'0') + ret;
>       current /= 10;
>    }
>
>    return ret;
> }
>  
> /*
> PLUG: http://plug.org, #utah on irc.freenode.net
> Unsubscribe: http://plug.org/mailman/options/plug
> Don't fear the penguin.
> */
>
>
>

Oops i'm double using my variable and not checking my bounds correctly 
for a negative number.

string itoa(int in) {
   string ret = "";
   int current = in;
   int digit = 0;

   while (current != 0 && digit = current % 10)
   {
      ret = (char)(digit+ (int)'0') + ret;
      current /= 10;
   }

   return ret;
}




More information about the PLUG mailing list