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

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

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

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

    boost::lexical_cast<std::string>(my_long) more here http://www.boost.org/doc/libs/1_39_0/libs/conversion/lexical_cast.htm

    0 讨论(0)
  • 2020-12-09 07:55
    int main()
    {
        long mylong = 123456789;
        string mystring;
        stringstream mystream;
        mystream << mylong;
        mystring = mystream.str();
        cout << mystring << "\n";
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-09 07:55

    Check out std::stringstream.

    0 讨论(0)
  • 2020-12-09 08:00

    The way I typically do it is with sprintf. So for a long you could do the following assuming that you are on a 32 bit architecture:

    char buf[5] = {0}; // one extra byte for null    
    sprintf(buf, "%l", var_for_long);
    
    0 讨论(0)
  • 2020-12-09 08:01

    You can use std::to_string in C++11

    long val = 12345;
    std::string my_val = std::to_string(val);
    
    0 讨论(0)
  • 2020-12-09 08:02

    I don't know what kind of homework this is, but most probably the teacher doesn't want an answer where you just call a "magical" existing function (even though that's the recommended way to do it), but he wants to see if you can implement this by your own.

    Back in the days, my teacher used to say something like "I want to see if you can program by yourself, not if you can find it in the system." Well, how wrong he was ;) ..

    Anyway, if your teacher is the same, here is the hard way to do it..

    std::string LongToString(long value)
    {
      std::string output;
      std::string sign;
    
      if(value < 0)
      {
        sign + "-";
        value = -value;
      }
    
      while(output.empty() || (value > 0))
      {
        output.push_front(value % 10 + '0')
        value /= 10;
      }
    
      return sign + output;
    }
    

    You could argue that using std::string is not "the hard way", but I guess what counts in the actual agorithm.

    0 讨论(0)
提交回复
热议问题