1

How can i replace this

    itoa(i, buf, 10);
    key1.append(buf);
    key2.append(buf);
    key3.append(buf);

with std::to_string

itoa was giving me an error it was not declared in scope that its not part of standard

I heard i can use std::to_string to make another version of it how do i do this?

soniccool
  • 5,790
  • 22
  • 60
  • 98
  • 2
    Here's a [reference](http://en.cppreference.com/w/cpp/string/basic_string/to_string). It even includes an example. – chris Dec 10 '12 at 05:02
  • What exactly is the problem? Doesn't `std::to_string(i)` solve it? Is the problem that this creates a `std::string`, but you need a `char *`? – jogojapan Dec 10 '12 at 05:43
  • @jogojapan - this would be possible only with C++11 right? – user93353 Dec 10 '12 at 07:27
  • Yes, `std::to_string` only exists in C++11. If you are looking for a solution that works with C++98/03, you can't use `std::to_string`. `boost::lexical_cast` is often recommended as alternative (but requires that you include the relevant headers from the Boost library). And of course `std::ostringstream` as mentioned in the answers is another alternative. – jogojapan Dec 10 '12 at 07:33

2 Answers2

4

If you use C++11, you can use std::to_string

#include <string>
std::string buf = std::to_string(i);
key1.append(buf);
key2.append(buf);
key3.append(buf);

or you could just use std:stringstream

#include <sstream>
std::stringstream ss;
ss << i;
key1.append(ss.str());
key2.append(ss.str());
key3.append(ss.str());
billz
  • 44,644
  • 9
  • 83
  • 100
-1

To use itoa() function, you need to include stdlib.h file, then you will not see the error while using itoa().

Rock
  • 19
  • 2
  • 2
    As the question says, `itoa` isn't part of the standard and may not be available; in which case, you will get the error. – Mike Seymour Dec 10 '12 at 07:56