Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error:‘itoa’ was not declared in this scope [duplicate]

Tags:

c++

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 ---
like image 392
Green goblin Avatar asked Jun 16 '12 12:06

Green goblin


People also ask

Which header has itoa?

C Programming/stdlib. h/itoa The itoa (integer to ASCII) function is a widespread non-standard extension to the standard C programming language. It cannot be portably used, as it is not defined in any of the C language standards; however, compilers often provide it through the header <stdlib.

Does itoa exist in C?

As itoa() is not standard in C, various versions with various function signatures exists. char *itoa(int value, char *str, int base); is common in *nix. Should it be missing from Linux or if code does not want to limit portability, code could make it own.

Does GCC support itoa?

itoa() is not ANSI-C defined and it not part of C++, and C32 is GCC based, and it is not really supported in GCC.


2 Answers

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

like image 109
juanchopanza Avatar answered Oct 13 '22 17:10

juanchopanza


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.

like image 7
pmr Avatar answered Oct 13 '22 17:10

pmr