C++ - Tips'n Tricks - Converting a std:string into an int and converting an int to a std::string

For the C, we had the famous atoi() function, but for C++, how can I convert a std::string into an int?

That's a great question, and the answer is easy, with the std::stringstream type element.
In this tutorial, we will see how to convert a std::string into an int and how to convert an int to a std::string.
 
Let's start by converting a string into a number (an int):

1. Converting a std::string into an int

So, let's take an example of this conversion:
 
#include <sstream>

#include <string>

#include <iostream>


int main (void) {

std::string myString = "100";

int result;


std::stringstream convertThis(myString);


if (!(convertThis >> result))

    result = 0;

result += 5;

std::cout << "Result = " << result << std::endl;

}
 
The result will be:
 
$ Result = 105
 
Indeed, I once the result is converted in an int, we can use it as it.
In our case, we use it to add 5 to the original int.

2. Converting an int into a std::string

So, let's take an example of this conversion:
 
#include <sstream>


#include <string>


#include <iostream>



int main (void) {


int myNumber = 250;


std::string myString;



std::stringstream convertThis;


convertThis << myNumber;


myString = convertThis.str();



std::string newString = "I saw ";


newString += myString;


newString += " birds in the sky!";



std::cout << newString << std::endl;


}
The result will be:
 
$ I saw 250 birds in the sky!
 
Indeed, I once the result is converted into a std::string, we can use it as it.
In our case, we use it to add "250" to the original std::string.
 

 

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.