ABC to Convert Integers to Strings in C++

I was solving a problem in TopCoder. It required a conversion of  integer to a string. This is simple in Java but a little complicated in C++. So, I am jotting down here some of the link that helped me. I will also try to make a mention of the problem associated with them.

The first one – itoa. Well, itoa considered unsafe to use this in C++. You may get an error like ” itoa was not declared in the scope “. I got stuck with the same error. It was then I started searching for solutions. The link following is about itoa. Note that, itoa doesn’t work in TopCoder.

http://www.cplusplus.com/reference/clibrary/cstdlib/itoa/

The next link use boost and a string stream. Again, the header file “boost/lexical_cast.hpp” is not detected by TopCoder.

http://ubuntuforums.org/showthread.php?t=271660

So, I feel, more or less the best way is to have you own customized code.

string convertInt(int number)
{
    if (number == 0)
        return "0";
    string temp="";
    string returnvalue="";
    while (number>0)
    {
        temp+=number%10+48;
        number/=10;
    }
    for (int i=0;i<temp.length();i++)
        returnvalue+=temp[temp.length()-i-1];
    return returnvalue;
}

The following link has more information about it.

http://www.cplusplus.com/forum/beginner/7777/

If you have any doubt, post in them as comments.

In Java, you can go about with some code like the following. Note, ‘s’ is a String and ‘a’,’ b’ and ‘c’ are Integers.

s = a + ” ” + b + ” ” + c;

Though something like above is possible in C++, it requires ‘a’,’ b’ and ‘c’ to be Strings.

Happy coding ! 🙂

boost/lexical_cast.hppboost/lexical_cast.hpp
Advertisements

2 Comments »

  1. superdrupermegapuper54321…

    Very usefull info. Thanks!…

  2. 2
    navin agarwal Says:

    We can use sprintf for this work. It is very simple and works in topcoder.

    The following link has information about how to use it

    http://cplusplus.com/reference/clibrary/cstdio/sprintf/


RSS Feed for this entry

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: