How to convert long to string in c++

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kirubagari
    New Member
    • Jun 2007
    • 158

    How to convert long to string in c++

    Dear Expert,

    Kindly need help on conversion of long to string.
    Code:
    long i = 123444788 to convert to string i.str();
      cout<< i.str();
    This is not functioning.Kin dly help me
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Long is a POD type not a class so it has no methods.

    But you don't need to convert to a string, the cout object knows how to handle longs so you can just

    Code:
        cout << i;

    Comment

    • whodgson
      Contributor
      • Jan 2007
      • 542

      #3
      a question to Banfa:
      But assuming the OP wants to convert the long to a string - how would you do that?

      Comment

      • johny10151981
        Top Contributor
        • Jan 2010
        • 1059

        #4
        you can follow several ways,
        like

        1. ltoa
        2.
        Code:
        char temp[20];
        long ld;
        sprintf(temp,"%ld",ld);

        Comment

        • Banfa
          Recognized Expert Expert
          • Feb 2006
          • 9067

          #5
          Yes or you could do it the C++ way using a string stream. An ostringstream acts exactly like the cout object so if you know how to use one you know how to use both.

          Code:
          #include <sstream>
          #include <iostream>
          #include <string>
          
          using namespace std;
          
          int main()
          {
              long i = 123444788;
              ostringstream oss;
          
              oss << i.str();
          
              string myString = oss.str();
          
              cout << myString;
          
              return 0;
          }

          In our systems I have started making methods to dump an objects status (mainly for debugging) that takes ostream& as an input. ostream is the base class of cout, cerr, clog, ofstream and ostringstream (see http://www.cplusplus.com/reference/iostream/) and an ostream& can be used exactly as you would use cout. In this way I can send the object dump directly to the screen, directly to a file or into a string for the code to do something else with (transmit over a network for example).

          The objects dumping there status do not need to know (on the whole) where the out is going, only that output is required. This is a fine example of the polymorphic nature of C++.
          Last edited by Banfa; Jun 9 '11, 12:46 PM.

          Comment

          • whodgson
            Contributor
            • Jan 2007
            • 542

            #6
            Thanks Banfa...I need to become more familiar with this subject.

            Comment

            Working...