Whats the easiest way to do that?
This is a discussion on Long to string, string to long conversion. within the C++ Programming forums, part of the General Programming Boards category; Whats the easiest way to do that?...
Whats the easiest way to do that?
Stringstreams:
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():Code:#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; }
But there is no simple inverse of that.Code:#include <cstdlib> string s("123"); int n = strtol(s.c_str(), NULL, 0);
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
or you could use boost::lexical_cast, and accept the fact that it has already been done![]()
Requires boost, which you should have anyway (boost.org).Code: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);
For information on how to enable C++11 on your compiler, look here.
よく聞くがいい!私は天才だからね! ^_^