OneBite.Dev - Coding blog in a bite size

Convert Variable From String To Int In C++

Code snippet for how to Convert Variable From String To Int In C++ with sample and detail explanation

C++ is a statically typed language which means the type of variable has to be known at compile time. However, sometimes you may need to convert a variable from string to int. This article will guide you on how to do this.

Simple code snippet for converting string to int in C++

Here is a simple code snippet in C++ that converts a string to int:

#include <iostream>
#include <string> 
using namespace std; 

int main() 
{ 

    string str = "1234"; 
    int num; 

    num = stoi(str);

    cout << num << endl; 

    return 0; 
}

Code Explanation for converting string to int in C++

In the above code, we are first including the essential libraries which are iostream for input-output operations and string for using string data type.

The using namespace std; line simplifies our access to different functions and classes in the standard namespace. main() is the entry point of our program.

In main(), we declare a variable ‘str’ of type string and assign the value “1234” to it. We also declare a variable ‘num’ of integer type which will later hold the converted integer value.

Then, the function stoi(str) is used to convert the string ‘str’ to an integer. This function is built-in in C++ and can be used for converting a string to an integer.

The converted value is assigned to ‘num’. On executing the code, the integer value is displayed on the console.

This way, a string can be successfully converted to an integer in C++. Remember to always conduct proper input validation to ensure that the string can be converted to an integer before applying this method because if the string consists of non-numeric characters, this function will throw an exception.

c-plus-plus