C++ String to int and vice versa

C++ string to int Conversion

We can convert string to int in multiple ways. The easiest way to do this is by using the std::stoi() function introduced in C++11.


Example 1: C++ string to int Using stoi()

#include <iostream>
#include <string>

int main() {

    std::string str = "123";
    int num;

    // using stoi() to store the value of str1 to x
    num = std::stoi(str);

    std::cout << num;

    return 0;
}

Output

123

Example 2: char Array to int Using atoi()

We can convert a char array to int using the std::atoi() function. The atoi() function is defined in the cstdlib header file.

#include <iostream>

// cstdlib is needed for atoi()
#include <cstdlib>

using namespace std;

int main() {

    // declaring and initializing character array
    char str[] = "456";
    int num = std::atoi(str);

   std::cout << "num = " << num;
    
    return 0;
}

Output

num = 456

To learn other ways of converting strings to integers, visit Different Ways to Convert C++ string to int


C++ int to string Conversion

We can convert int to string using the C++11 std::to_string() function. For older versions of C++, we can use std::stringstream objects.


Example 3: C++ int to string Using to_string()

#include <iostream>
#include <string>

using namespace std;

int main() {
    int num = 123;
    
    std::string str = to_string(num);

    std::cout << str;

    return 0;
}

Output

123

Example 4: C++ int to string Using stringstream

#include <iostream>
#include<string>
#include<sstream> // for using stringstream

using namespace std;

int main() {
    int num = 15;
  
    // creating stringstream object ss
    std::stringstream ss;
  
    // assigning the value of num to ss
    ss << num;
  
    // initializing string variable with the value of ss
    // and converting it to string format with str() function
    std::string strNum = ss.str();
    std::cout << strNum;

    return 0;
}

Output

15

To know about converting a string to float/double, visit C++ String to float/double.

Did you find this article helpful?

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community