开发者

How do I convert from int to chars in C++?

开发者 https://www.devze.com 2023-01-28 04:00 出处:网络
i want transfor开发者_如何学Cmation from int to char(or string) in c++.Apart from using stringstream directly, you can also use boost::lexical_cast:

i want transfor开发者_如何学Cmation from int to char(or string) in c++.


Apart from using stringstream directly, you can also use boost::lexical_cast:

std::string x = boost::lexical_cast<std::string>(42);


The simplest way to convert any basic data type to char* is with sprintf:

char mystring[MAX_SIZE];
sprintf(mystring, "%d", my_int);


Well, that is not specially complex:

#include <sstream>

    std::string cnvt(int x)
    {
        std::ostringstream cnvt;

        cnvt << x;

        return cnvt.str();
    }

Hope this helps.


#include <sstream>

ostringstream intStream;
int myInt(123456);

intStream << myInt;

string myIntString(intStream.str());


Since C++11 you don't need boost, sprintf() or std::ostringstream. You can simply write:

#include <string>

std::string str = std::to_string(1077);

or

std::wstring wstr = std::to_wstring(1077);
0

精彩评论

暂无评论...
验证码 换一张
取 消