Compdigitec Labs

« | Home | »

Converting between int and std::string in C++

By admin | November 20, 2010

#include <iostream>
#include <sstream>
#include <cstdlib>
using namespace std;

int main() {
	// convert int to string
	int some_int = 52;
	stringstream ss;
	ss << some_int;
	string result_s;
	ss >> result_s;
	// result_s = 52
	cout << result_s << endl;

	// convert string to int
	string some_string = "1234";
	int result_i = atoi(some_string.c_str());
	// result_i = 1234
	cout << result_i << endl;
}

If you found this article helpful or interesting, please help Compdigitec spread the word. Don’t forget to subscribe to Compdigitec Labs for more useful and interesting articles!

Topics: Linux, Windows | 2 Comments »

2 Responses to “Converting between int and std::string in C++”

  1. Russell Says:
    September 14th, 2011 at 8:42 am

    What about converting from std::string back to int

  2. admin Says:
    April 28th, 2012 at 7:13 pm

    @Russell:

    See atoi() or sscanf() in the C standard library.

Comments