9

I am getting the following error:
prog.cpp: In member function ‘void Sequence::GetSequence()’:
prog.cpp:45: error: ‘itoa’ was not declared in this scope

I have include cstdlib header file but its not working.

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <functional>
using namespace std;

template<typename T>
struct predicate :
public binary_function<T, T, bool>
{
    bool operator() (const T& l,const T &r) const
    {
          return l < r;
    }
};

class Sequence
{
    public:
    Sequence(vector<string> &v)
    { /* trimmed */ }

void GetSequence(void)
{
    string indices = "";
    char buf[16];

    for( map<int, string>::iterator
            i = m.begin(); i != m.end(); ++i )
    {
indices = indices
                  + string(itoa((i->first), buf, 10));
    }

    SortedSequence("", indices);
}

// --- trimmed ---
CB Bailey
  • 755,051
  • 104
  • 632
  • 656
Green goblin
  • 9,898
  • 13
  • 71
  • 100
  • What if you add `#include `? –  Jun 16 '12 at 12:28
  • 2
    @H2CO3: `itoa` is not (a standard) declaration in `cstdlib`. – CB Bailey Jun 16 '12 at 12:30
  • 1
    @CharlesBailey: not a dupe; the other question is about C. – Fred Foo Jun 16 '12 at 12:38
  • @larsmans: I think that's being a little pedantic. `atoi` is part of C++ thanks to inheriting C library functions. Clearly the expectation is that `itoa` would come from the same place. In fact `itoa` is not part of the C library. Of course, neither is it a non-C addition that C++ provides. – CB Bailey Jun 16 '12 at 12:43
  • 1
    @CharlesBailey: that final remark is quite important, though. Besides, C++ provides different alternatives to `itoa` than C, so there is a practical difference. – Fred Foo Jun 16 '12 at 12:46

3 Answers3

15

There's no itoa in the standard, but in C++11 you can use the std::to_string functions.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
7

In C++11 you can use std::to_string. If this is not available to you, you can use a std::stringstream:

std::stringstream ss; int x = 23;
ss << x;
std::string str = ss.str();

If this is too verbose, there is boost::lexical_cast. There are some complaints about the performance of lexical_cast and std::stringstream, so watch out if this is important to you.

Another option is to use a Boost.Karma, a sublibrary of Spirit. It comes out ahead in most benchmarks.

Usually, itoa is a bad idea. It is neither part of the C nor C++ standard. You can take some care to identify the platforms that support it and use it conditionally, but why should you, when there are better solutions.

pmr
  • 58,701
  • 10
  • 113
  • 156
3

I've found that itoa was not available in MinGW GCC at least until 4.9.3 but is available in MinGW-w64 GCC 5.3.0.

It guess it's absense was related to broken vswprintf issue which also caused missing std::stoi and std::to_string in MinGW.

Vadzim
  • 24,954
  • 11
  • 143
  • 151