How do I convert a long to a string in C++?

后端 未结 12 1257
慢半拍i
慢半拍i 2020-12-09 07:12

How do I convert a long to a string in C++?

相关标签:
12条回答
  • 2020-12-09 07:44

    You could use stringstream.

    #include <sstream>
    
    // ...
    std::string number;
    std::stringstream strstream;
    strstream << 1L;
    strstream >> number;
    

    There is usually some proprietary C functions in the standard library for your compiler that does it too. I prefer the more "portable" variants though.

    The C way to do it would be with sprintf, but that is not very secure. In some libraries there is new versions like sprintf_s which protects against buffer overruns.

    0 讨论(0)
  • 2020-12-09 07:48

    In C++11, there are actually std::to_string and std::to_wstring functions in <string>.

    string to_string(int val);
    string to_string(long val);
    string to_string(long long val);
    string to_string(unsigned val);
    string to_string(unsigned long val);
    string to_string(unsigned long long val);
    string to_string(float val);
    string to_string(double val);
    string to_string (long double val);
    
    0 讨论(0)
  • 2020-12-09 07:48
       #include <sstream>
    
    
       ....
    
        std::stringstream ss;
        ss << a_long_int;  // or any other type
        std::string result=ss.str();   // use .str() to get a string back
    
    0 讨论(0)
  • 2020-12-09 07:51

    There are several ways. Read The String Formatters of Manor Farm for an in-depth comparison.

    0 讨论(0)
  • 2020-12-09 07:52

    One of the things not covered by anybody so far, to help you think about the problem further, is what format should a long take when it is cast to a string.

    Just have a look at a spreedsheet program (like Calc/Excel). Do you want it rounded to the nearest million, with brackets if it's negative, always to show the sign.... Is the number realy a representation of something else, should you show it in Oractal or Hex instead?

    The answers so far have given you some default output, but perhaps not the right ones.

    0 讨论(0)
  • 2020-12-09 07:54

    Well if you are fan of copy-paste, here it is:

    #include <sstream>
    
    template <class T>
    inline std::string to_string (const T& t)
    {
        std::stringstream ss;
        ss << t;
        return ss.str();
    }
    
    0 讨论(0)
提交回复
热议问题