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 | 9 Comments »

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

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

    What about converting from std::string back to int

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

    @Russell:

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

  3. pic 5678 Says:
    September 3rd, 2021 at 18:26

    … [Trackback]

    […] Information to that Topic: compdigitec.com/labs/2010/11/20/converting-between-int-and-string-in-c/ […]

  4. dark0de market link Says:
    September 16th, 2021 at 13:09

    … [Trackback]

    […] Find More to that Topic: compdigitec.com/labs/2010/11/20/converting-between-int-and-string-in-c/ […]

  5. kardinal stick Says:
    November 9th, 2021 at 20:53

    … [Trackback]

    […] There you can find 68895 more Info to that Topic: compdigitec.com/labs/2010/11/20/converting-between-int-and-string-in-c/ […]

  6. newsbloger Says:
    November 25th, 2021 at 10:57

    … [Trackback]

    […] Find More here to that Topic: compdigitec.com/labs/2010/11/20/converting-between-int-and-string-in-c/ […]

  7. สล็อตเว็บตรง Says:
    December 26th, 2021 at 04:24

    … [Trackback]

    […] Find More here to that Topic: compdigitec.com/labs/2010/11/20/converting-between-int-and-string-in-c/ […]

  8. relx Says:
    December 27th, 2021 at 19:24

    … [Trackback]

    […] Find More to that Topic: compdigitec.com/labs/2010/11/20/converting-between-int-and-string-in-c/ […]

  9. Guns For Sale Says:
    January 5th, 2022 at 03:28

    … [Trackback]

    […] Find More Information here to that Topic: compdigitec.com/labs/2010/11/20/converting-between-int-and-string-in-c/ […]

Comments