English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ String (string) and int (integer) interconversion

In this tutorial, we will learn how to convert String (string) and int (integer) by using examples.

C ++string (string) to int (integer)

We can convert string and int in many ways. The simplest method is to useC ++ 11instd::stoi() introduced features.

Example1: Use stoi() to convert C ++Convert string to int

#include <iostream>
#include <string>
int main() {
    std::string str = "123";
    int num;
    // Use stoi() to convert str1The value is stored in x
    num = std::stoi(str);
    std::cout << num;
    return 0;
}

Output Result

123

Example2: Use atoi() to convert a char array to int

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

#include <iostream>
// atoi() requires std::cstdlib
#include <cstdlib>
using namespace std;
int main() {
    // Declare and initialize a character array
    char str[] = "456";
    int num = std::atoi(str);
   std::cout << "num = " << num;
    
    return 0;
}

Output Result

num = 456

C ++ int (integer) to string (string)

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

Example3: Use to_string() to convert C ++ Convert int 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 Result

123

Example4: Use stringstream to convert C ++ Convert int to string

#include <iostream>
#include <string>
#include <sstream> // To use stringstream
using namespace std;
int main() {
    int num = 15;
  
    // Create a stringstream object ss
    std::stringstream ss;
  
    // Assign the value of num to ss
    ss << num;
  
     //Initialize the string variable with the value of ss
     //Then use the str() function to convert it to string format
    std::string str = ss.str();
    std::cout << str;
    return 0;
}

Output Result

15

To learn about converting strings to float / For information on double, please visitC ++ String Conversion to float / double.