Thread: Long to string, string to long conversion.

  1. #1
    Registered User
    Join Date
    Mar 2011

    Long to string, string to long conversion.

    Whats the easiest way to do that?

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    segmentation fault

    #include <iostream>
    #include <string>
    #include <sstream>
    using namespace std;
    int main(int argc, char *argv[]) {
    // long to string
    	int n = 123456789;
    	ostringstream oss;
    	oss << n;
    	string s(oss.str());
    	cout << s << endl;
    // string to long
    	n = 0;
    	istringstream iss(s);
    	iss >> n;
    	cout << n << endl;
    	return 0;
    If you only have to do it once and don't want to instantiate the stringstream you could use a standard C function like strtol():

    #include <cstdlib>
    string s("123");
    int n = strtol(s.c_str(), NULL, 0);
    But there is no simple inverse of that.
    Last edited by MK27; 06-28-2011 at 10:36 AM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  3. #3
    Registered User
    Join Date
    Oct 2006
    or you could use boost::lexical_cast, and accept the fact that it has already been done

  4. #4
    Join Date
    Oct 2007
    Inside my computer
    int n = boost::lexical_cast<int>(std::string("1234")); // Works on regular C-style strings, too
    std::string s = boost::lexical_cast<std::string>(1234);
    Requires boost, which you should have anyway (
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 10-11-2010, 01:53 AM
  2. unsigned long long to string conversion
    By Wiretron in forum C++ Programming
    Replies: 6
    Last Post: 12-21-2007, 04:02 AM
  3. unsigned long long to string
    By DV64h in forum C++ Programming
    Replies: 10
    Last Post: 09-30-2006, 05:17 AM
  4. double, long, int ==> string conversion
    By mangoMan in forum C++ Programming
    Replies: 1
    Last Post: 07-29-2004, 07:38 AM
  5. char string to long conversion
    By rastan in forum C Programming
    Replies: 10
    Last Post: 11-06-2003, 07:28 PM