What is the difference between _itoa and itoa?

前提是你 提交于 2019-12-03 07:14:57

A C run time library implementation is not supposed to introduce names that aren't in the standard unless they follow a certain naming convention (like starting with an underscore). The earlier versions of Microsoft's compiler didn't follow this rule particularly closely, but over time, Microsoft has been moving more toward making their implementation more standards compliant. So functions they used to supply that would intrude on the user's namespace they have been implementing using names that are reserved for compiler implementations and have been deprecating the old names.

If _CRT_NONSTDC_NO_WARNINGS is defined, the MS compiler won't complain about the itoa() function being deprecated. But it will still complain about it being unsafe (you have to define _CRT_SECURE_NO_WARNINGS to quiet that warning). Or use the safer version of the function (_itoa_s()) that provides the function with the destination buffer size

Both _itoa() and itoa() resolve to the exact same function in the library down to the same address - there is no difference except in the name.

The MSDN documentation for itoa() says:

This POSIX function is deprecated beginning in Visual C++ 2005. Use the ISO C++ conformant _itoa or security-enhanced _itoa_s instead.

itoa is not standard C.

"This function is not defined in ANSI-C and is not part of C++, but is supported by some compilers." - cplusplus.com

So MSVS is telling you to use the _itoa to tell you that it is not standard C++ and that you should mark it as such. I believe that it is there for backwards compatibility and that this notation is for readability and distinction.

itoa is not standard, so you should use stringstream instead.

you'll need #include <sstream>

an example of it's use would be:

int i = 5;
std::stringstream ss;

ss << i;

std:: cout << ss.str();

In reply to the answer by Bruce:

itoa is not standard, so you should use stringstream instead.

you'll need #include <sstream>

an example of it's use would be:

int i = 5; std::stringstream ss;

ss << i;

std:: cout << ss.str();

You can also code your own itoa() function instead

eg:

const char* itoa (int num)
{
    if (num == 0)
    {
        return "0";
    }
    bool neg = false;
    if (num < 0)
    {
        neg = true;
        num = -num;
    }

    int digits = 0;
    int tmp = num;

    while (tmp > 0)
    {
        digits++;
        tmp /= 10;
    }

    int digs[digits];

    for (tmp = digits; num > 0; tmp--)
    {
        digs[tmp] = num % 10;
        num /= 10;
    }

    string s = neg == true ? "-" : "";
    for (tmp = 1; tmp <= digits; tmp++)
    {
        s += (char)(digs[tmp] + 48);
    }
    return s.c_str();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!