What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Convert string to int in C++: 3 Useful Methods (with code)

  • May 09, 2023
  • 6 Minute Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Anubhav Agarwal
Convert string to int in C++: 3 Useful Methods (with code)

Converting integers to strings always seems confusing to most the programmers at beginning. In this article, we are going to learn about how to convert string to int using various methods in C++.

What is int & string in C++?

There are many data types in C++, but two important ones are int & string. Let's first revise them a bit before moving on.

The int is a built-in data type that is used to represent integers or whole numbers. t can represent both positive and negative numbers. On the other hand, the string is a built-in data type that is used to represent a sequence of characters. It is defined in the header file. A string is basically an object that can store a sequence of characters, including letters, numbers, and punctuation.

We may want to convert a string to an int for various reasons. One important one is Input validation, where we take input for numerical value as a string and then convert it to an int to ensure that it is a valid numerical value. Also, sometimes when we have to process large amounts of data, we may need to read numbers from files, which are often represented as strings. 

How to convert string to int in C++?

There are multiple methods to achieve the conversion from string to int. We will discuss 3 common methods available in C++ programming:

  1. Using stoi() function
  2. Using atoi() function
  3. Using Stringstream

1) Using stoi() function

The best way to convert string to int in C++ is by using stoi function. The stoi, which stands for the string to integer, is part of the 'string' header. It takes a string as an argument and returns its value in integer form.

Learn more about stoi in C++ here.

 Consider the below example to completely understand the working of the stoi() function :

// Welcome to FavTutor
// C++ program to demonstrate working of stoi()
// Work only if compiler supports C++11 or above
// Because STOI() was added in C++ after 2011
#include<iostream>
#include<string>
using namespace std;

int main()
{
	string str1 = "45";
	string str2 = "3.14159";
	string str3 = "31337 geek";

	int myint1 = stoi(str1); // type of explicit type casting
	int myint2 = stoi(str2); // type of explicit type casting
	int myint3 = stoi(str3); // type of explicit type casting

	cout << "stoi(\"" << str1 << "\") is " << myint1
		<< '\n';
	cout << "stoi(\"" << str2 << "\") is " << myint2
		<< '\n';
	cout << "stoi(\"" << str3 << "\") is " << myint3
		<< '\n';

	return 0;
}

 

Output:

stoi("45") is 45
stoi("3.14159") is 3
stoi("31337 geek") is 31337

 

Let's consider another example:

// Welcome to FavTutor
#include<iostream>
#include<string>
using namespace std;

int main() {
   // a string variable named str
   string str = "7";
   //print to the console
   cout << "I am a string " << str << endl;

   //convert the string str variable to have an int value
   //place the new value in a new variable that holds int values, named num
   int num = stoi(str);
   
   //print to the console
   cout << "I am an int " << num << endl;
}

 

Output:

I am a string 7
I am an int 7

 

2) Using atoi() function

In C++, the atoi is a built-in function that converts a C-style string to an integer. It stands for "ASCII to integer", and it is defined in the header file. Here we perform explicit type casting. 

Consider the C++ code below to completely understand the working of the atoi() function: 

// C++ program to demonstrate the functioning of
// the ATOI() function
#include<cstdlib>
#include<iostream>
using namespace std;

int main()
{
	const char* str1 = "42";
	const char* str2 = "3.14159";
	const char* str3 = "31337 geek";

	int num1 = atoi(str1); // explicit type casting
	int num2 = atoi(str2); // explicit type casting
	int num3 = atoi(str3); // explicit type casting

	cout << "atoi(\"" << str1 << "\") is " << num1 << '\n';
	cout << "atoi(\"" << str2 << "\") is " << num2 << '\n';
	cout << "atoi(\"" << str3 << "\") is " << num3 << '\n';

	return 0;
}

 

Output:

atoi("42") is 42
atoi("3.14159") is 3
atoi("31337 geek") is 31337

 

Note that atoi() is a legacy C-style function, while stoi() is added in C++ 11. Basically, atoi() takes only one parameter and returns an integer value. The 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.

3) Using stringstream

The stringstream is a class defined in the 'sstream' header that allows you to treat strings as input/output streams. It is useful for many tasks, such as parsing a string to extract numerical values or formatting numerical values as a string. This is a method to convert string to int in C++ without stoi.

Since to access the data members and member functions of a class, we create an object first. Similarly, we will create an object of Stringstream class and we use different operators for conversions. We then take input or read a string from the string variable, then this stringstream object does some internal conversions from string to int and then we read an int value using int variable.

Here is a C++ example below:

// Welcome to FavTutor
// C++ program to demonstrate the
// use of a stringstream to
// convert string to int
#include<iostream>
#include<sstream>
using namespace std;

int main()
{
	string s = "12345";

	// object from the class stringstream
	stringstream favtutor(s);

	// The object has the value 12345 and stream
	// it to the integer x
	int x = 0;
	favtutor >> x;

	// Now the variable x holds the value 12345
	cout << "Value of x : " << x;

	return 0;
}

 

Output:

Value of x : 12345

 

Also, check out how to convert char to string in C++.

Conclusion

We hope you now have a complete understanding of the multiple methods to convert a string to int in C++. Congratulations on getting this far! Now give yourself a pat on the back. Good job!

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Anubhav Agarwal
I'm a research-oriented engaged in various technologies and a technical content writer. Being a coder myself, going through the documentation to provide optimized solutions as technical content is what I always look for.