Convert String to int in C++
Last Updated :
19 May, 2025
Converting a string to int is one of the most frequently encountered tasks in C++. As both string and int are not in the same object hierarchy, we cannot perform implicit or explicit type casting as we can do in case of double to int or float to int conversion. Conversion is mostly done so that we can convert numbers that are stored as strings.
Example:
Input: "191"
Output: 191
There are 6 significant methods to convert strings to numbers in C++ as follows:
1. String to int Conversion Using stoi() Function
The stoi() function in C++ takes a string as an argument and returns its value in integer form. This approach is popular in current versions of C++, as it was first introduced in C++11.
Breakdown of stoi() in simple termsSyntax:
C++
stoi(str, position, base);
Parameters:
- str: string to be converted. (compulsory)
- position: starting position. (optional with default value = 0)
- base: base of the number system. (optional with default value = 10)
For more on handling data types and conversions, check out our Complete C++ Course, where you’ll learn how to work with strings, numbers, and various conversions in C++.
Example:
C++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "45";
string str2 = "3.14159";
char str3[] = "31337 geek";
// Store the integer value which
// by stoi()
int myint1 = stoi(str1);
int myint2 = stoi(str2);
int myint3 = stoi(str3);
cout << "stoi(\"" << str1 <<
"\") is " << myint1 << '\n';
cout << "stoi(\"" << str2 <<
"\") is " << myint2 << '\n';
cout << "stoi(\"" << str3 <<
"\") is " << myint3;
return 0;
}
Outputstoi("45") is 45
stoi("3.14159") is 3
stoi("31337 geek") is 31337
2. String to int Conversion Using atoi()
The atoi() function in C++ takes a character array or string literal as an argument and returns its value in an integer. It is defined in the <stdlib.h> header file. This function is inherited by C++ from C language, so it only works on C style strings i.e. array of characters.
Breakdown of atoi() in simple termsSyntax:
C++
Example:
C++
#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
char str1[] = "141";
char str2[] = "3.14";
// Convert string into integer
// using atoi()
int res1 = atoi(str1);
int res2 = atoi(str2);
cout << "atoi(" << str1 << ") is " << res1 << "\n";
cout << "atoi(" << str2 << ") is " << res2;
return 0;
}
Outputatoi(141) is 141
atoi(3.14) is 3
stoi() vs atoi()
The differences between stoi() and atoi() are shown below:
stoi() | atoi() |
---|
stoi() is added in C++ 11. | atoi() is a legacy C-style function. |
stoi() works for both C++ strings and C-style strings (character array and string literal). | atoi() works only for C-style strings (character array and string literal). |
stoi() can take up to three parameters, the second parameter is for starting index and the third parameter is for the base of the input number. | atoi()takes only one parameter and returns an integer value. |
3. String to int Conversion Using stringstream Class
The stringstream class in C++ allows us to associate a string to be read as if it were a stream. We can use it to easily convert strings of digits into ints, floats, or doubles. The stringstream class is defined inside the <sstream> header file.
It works similar to other input and output streams in C++. We first create a stringstream object as shown below:
C++
Then insert a numeric string into it using the ( << ) insertion operator:
C++
ss << myString;
ss << myCstring;
At last, we extract the numeric value from the stream using the ( >> ) extraction operator:
C++
ss >> myChar;
ss >> myCstring;
The below C++ program demonstrates how to convert a string to int using a stringstream object:
C++
#include <iostream>
#include <sstream>
using namespace std;
int main() {
string s = "12345";
// object from the class stringstream
stringstream geek;
// inserting string s in geek stream
geek << s;
// The object has the value 12345
// and stream it to the integer x
int x = 0;
geek >> x;
// Now the variable x holds the
// value 12345
cout << "Value of x + 1 : " << x + 1;
return 0;
}
OutputValue of x + 1 : 12346
To summarize, stringstream is a convenient way to manipulate strings. This method also works for both C style strings or C++ style strings.
4. Converting String to int Using sscanf()
'sscanf()' is a C-style function similar to scanf(). It reads input from a string rather than standard input.
Syntax:
C++
sscanf(source, formatted_string, ...);
Parameters:
- source: source string.
- formatted_string: a string that contains the format specifiers.
- ... : variable arguments list that contains the address of the variables in which we want to store input data.
There should be at least as many of these arguments as the number of values stored by the format specifiers.
Return Value:
- On success, the function returns the number of variables filled.
- In the case of an input failure, before any data could be successfully read, the end of the function (EOF) is returned.
Example:
C++
#include <iostream>
using namespace std;
int main() {
const char* str = "12345";
int x;
sscanf(str, "%d", &x);
cout << "The value of x: " << x;
return 0;
}
OutputThe value of x: 12345
5. Using For Loop Convert Strings into int
It is the naive method of string to int conversion where we compare each character to its ASCII values and then get the value of that numeric character.
Example:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
string number = "13";
int i = 0;
// Traversing string
for (char c : number) {
// Checking if the element is number
if (c >= '0' && c <= '9') {
i = i * 10 + (c - '0');
}
// Otherwise print bad output
else {
cout << "Bad Input";
return 1;
}
}
cout << i;
}
Above program converts a string into an integer by iterating through each character, checking if it's a digit, and then calculating the integer value by updating the variable i as i = i * 10 + (c - '0') for each valid digit. Non-digit characters result in a "Bad Input" message and terminate the program.
6. String to int Conversion Using strtol()
The strtol function is used to converts a string to a long integer value, respectively.
Syntax:
C++
strtol(str, endptr, base);
Parameters:
- st: Pointer to the null-terminated string to be converted
- endptr: Reference to a pointer to character. The function stores the address of the first invalid character in *endptr. If endptr is a null pointer, the function does not store this information.
- base: The number base to interpret the string. Must be between 2 and 36, inclusive, or 0. If base is 0, the function determines the base from the string itself. If the base is 16, the string may begin with the prefix "0x" or "0X", in which case the number is parsed as a hexadecimal value.
Return Value:
- If the string is empty or does not contain any digits, 0 is returned.
- If the conversion is successful, the function returns the converted long integer value.
- If the conversion fails, the function returns 0 and sets *endptr to point to the beginning of the string.
Example:
C++
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[] = "12345";
char* endptr;
long int value = strtol(str, &endptr, 10);
if (endptr == str) {
printf("No digits were found\n");
} else if (*endptr != '\0') {
printf("Invalid input: %s\n", str);
} else {
printf("The value is %ld\n", value);
}
return 0;
}
Similar Reads
Convert String to size_t in C++
To convert String to size_t in C++ we will use stringstream, It associates a string object with a stream allowing you to read from the string as if it were a stream (like cin). We must include the stream header file in order to use stringstream. When parsing input, the stringstream class comes in qu
1 min read
Converting Number to String in C++
In C++, converting integers to strings or converting numbers to strings or vice-versa is actually a big paradigm shift in itself. In general or more specifically in competitive programming there are many instances where we need to convert a number to a string or string to a number. Let's look at som
4 min read
std::to_string in C++
In C++, the std::to_string function is used to convert numerical values into the string. It is defined inside <string> header and provides a simple and convenient way to convert numbers of any type to strings.In this article, we will learn how to use std::to_string() in C++.Syntaxstd::to_strin
1 min read
How to Convert Vector of int into String?
In C++, there are numerous cases where a vector of integers is needs to be converted into a string. In this article, we will learn the different methods to convert the vector of int into string in C++.The simplest method to convert the vector of int into string is by creating a stringstream and addi
3 min read
C++ Program to Convert String to Integer
Given a string of digits, the task is to convert the string to an integer. Examples: Input : str = "12345" Output : 12345 Input : str = "876538"; Output : 876538 Input : str = "0028"; Output : 28 CPP // C++ program to convert String into Integer #include <bits/stdc++.h> using namespace std; //
1 min read
Convert a floating point number to string in C
Write a C function ftoa() that converts a given floating-point number or a double to a string. Use of standard library functions for direct conversion is not allowed. The following is prototype of ftoa(). The article provides insight of conversion of C double to string. ftoa(n, res, afterpoint) n --
3 min read
Conversion Operators in C++
In C++, the programmer abstracts real-world objects using classes as concrete types. Sometimes, it is required to convert one concrete type to another concrete type or primitive type implicitly. Conversion operators play an important role in such situations. It is similar to the operator overloading
4 min read
Type Conversion in C++
Type conversion means converting one type of data to another compatible type such that it doesn't lose its meaning. It is essential for managing different data types in C++. Let's take a look at an example:C++#include <iostream> using namespace std; int main() { // Two variables of different t
4 min read
strtol() function in C++ STL
The strtol() function is a builtin function in C++ STL which converts the contents of a string as an integral number of the specified base and return its value as a long int. Syntax: strtol(s, &end, b) Parameters: The function accepts three mandatory parameters which are described as below: s: s
4 min read
strol() function in C++
The strtol() function in C++ interprets the contents of a string as an integral number of the specified base and return its value as a long int.This function also sets an end pointer that points to the first character after the last valid numeric character of the string, if there is no such characte
3 min read