- How to convert a string to an int in C++
- 1. Using the stringstream class
- 2. Using stoi()
- 3. Using atoi()
- Convert String to Int Array in C++
- Use std::getline and std::stoi Functions to Convert string to int Array in C++
- Use std::string::find and std::stoi Functions to Convert string to int Array in C++
- Use std::copy and std::remove_if Functions to Convert string to int Array in C++
- Related Article — C++ String
- String to int in C++
- C++ Data Types
- String Conversion Techniques in C++
- Using stoi()
- Using atoi()
- Using stringstream
- Difference between stoi() and atoi()
- Conclusion
- Read More:
How to convert a string to an int in C++
Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2023 with this popular free course.
There are certain instances in C++ programming when it is necessary to convert a certain data type to another; one such conversion is from a string to an int .
Let’s have a look at a few of the ways to convert a string to an int :
1. Using the stringstream class
The stringstream class is used to perform input/output operations on string-based streams. The > operators are used to extract data from( into ( >> ) the stream. Take a look at the example below:
#include#includeusing namespace std;int main()string str = "100"; // a variable of string data typeint num; // a variable of int data type// using the stringstream class to insert a string and// extract an intstringstream ss;ssss >> num;coutcout>2. Using stoi()
The stoi() function takes a string as a parameter and returns the integer representation. Take a look at the example below:
#include#includeusing namespace std;int main()// 3 string examples to be used for conversionstring str_example_1 = "100";string str_example_2 = "2.256";string str_example_3 = "200 Educative";// using stoi() on various kinds of inputsint int_1 = stoi(str_example_1);int int_2 = stoi(str_example_2);int int_3 = stoi(str_example_3);coutcoutcout>3. Using atoi()
The atoi() function is different from the stoi() function in a few ways. First, atoi() converts C strings (null-terminated character arrays) to an integer, while stoi() converts the C++ string to an integer. Second, the atoi() function will silently fail if the string is not convertible to an int , while the stoi() function will simply throw an exception.
Take a look at the usage of atoi() below:
Convert String to Int Array in C++
- Use std::getline and std::stoi Functions to Convert string to int Array in C++
- Use std::string::find and std::stoi Functions to Convert string to int Array in C++
- Use std::copy and std::remove_if Functions to Convert string to int Array in C++
This article will demonstrate multiple methods about how to convert string to int array in C++.
Use std::getline and std::stoi Functions to Convert string to int Array in C++
std::stoi is used to convert string values to a signed integer, and it takes one mandatory argument of type std::string . Optionally, the function can take 2 additional arguments, the first of which can be used to store the index of the last unconverted character. The third argument can optionally specify the number base of the input. Note that we assume the comma-separated numbers as the input string like .csv file. Thus, we use the getline function to parse each number and then pass the value to the stoi . We also store each number in the std::vector container by calling the push_back method on every iteration.
#include #include #include #include using std::cout; using std::cerr; using std::endl; using std::string; using std::vector; using std::stringstream; using std::stoi; int main(int argc, char *argv[]) string text = "125, 44, 24, 5543, 111"; vectorint> numbers; int num; stringstream text_stream(text); string item; while (std::getline(text_stream, item, ',')) numbers.push_back(stoi(item)); > for (auto &n : numbers) cout
> exit(EXIT_SUCCESS); > Use std::string::find and std::stoi Functions to Convert string to int Array in C++
Alternatively, we can utilize a find built-in method of the std::string class to retrieve the position of the comma delimiter and then call the substr function to get the number. Then, the substr result is passed to the stoi which itself is chained to push_back method to store the number into the vector . Note that there’s the line after the while loop which is necessary to extract the last number in the sequence.
#include #include #include #include using std::cout; using std::cerr; using std::endl; using std::string; using std::vector; using std::stringstream; using std::stoi; int main(int argc, char *argv[]) string text = "125, 44, 24, 5543, 111"; vectorint> numbers; size_t pos = 0; while ((pos = text.find(',')) != string::npos) numbers.push_back(stoi(text.substr(0, pos))); text.erase(0, pos + 1); > numbers.push_back(stoi(text.substr(0, pos))); for (auto &n : numbers) cout
> exit(EXIT_SUCCESS); > Use std::copy and std::remove_if Functions to Convert string to int Array in C++
Another method to extract integers is to use std::copy algorithm in conjunction with std::istream_iterator and std::back_inserter . This solution stores the string values into a vector and outputs them to the cout stream, but one can easily add std::stoi function to convert each element to int value. Mind though, that the following example code only stores the numbers as string values.
#include #include #include #include using std::cout; using std::cerr; using std::endl; using std::string; using std::vector; using std::stringstream; using std::stoi; int main(int argc, char *argv[]) string text = "125, 44, 24, 5543, 111"; vectorstring> nums; std::istringstream iss(text); copy(std::istream_iteratorstring>(iss), std::istream_iteratorstring>(), std::back_inserter(nums)); for (auto &n : nums) n.erase(std::remove_if(n.begin(), n.end(), ispunct), n.end()); cout
> exit(EXIT_SUCCESS); > Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
Related Article — C++ String
String to int in C++
Strings are an array of characters. We can convert a string to int C++ using stoi() , atoi() , or stringstream . The header file for stoi() is , for atoi() and stringstream is .
C++ Data Types
To convert string to int C++, let’s understand some data types. In C++, data is stored using a variety of data types. The type of data used to hold a value impacts how it can be modified.
String operations, for example, can be used to manipulate the contents of strings but not with numerical numbers.
These are some of the data types in C++:
Data type Value Stored Example int Integer 1, 2, 3, 10, 100 char Characters ‘a’, ‘b’, ‘#’ bool True/False true or false, 0 or 1 float Decimal 1.03, 3.140, 8.1145 array Continous group of same data type string Continous group of characters «abcd» String Conversion Techniques in C++
Suppose you are reading a file that contains a list of numbers. When you read this file, you get these numbers in text format, but it’s difficult to do numerical processing on the string, right? That’s why C++ provides us with functions to convert a string to an integer.
Using stoi()
To convert string to int c++, stoi() can be used, a function that extracts integers from a string.
Parameters: The stoi() function accepts a string as an argument. Return value : The stoi() function returns an integer value. Header file:
The stoi() function accepts a string as an argument and converts the string’s integer component to an integer type. It will only consider integer values until the first non-integer character or the end of the string.
Let’s understand string to int c++ with sample code:
Explanation:
- In the first string str1 = «42» , stoi(str1) converts all the integer values of str1 to int and stores them in num1 .
- In the second string str2 = «54 fifty four» ; stoi(str2) converts all the integer values of str2 till the first non-integer value that is space » » to int and stores them in num2 .
- In the third-string str3 = «62 sixty-two 54″ ; stoi(str3) converts all the integer values of str1 till the first non-integer value that is space » » to int and stores them in num3.
But let’s take a case when the first value is a non-integer value.
Explanation: This will give a runtime error. This is because when stoi() hits a non-integer value or a white space, it terminates while traversing. If the starting character is a non-integer value, the stoi() function terminates, giving an error as shown in the output.
Using atoi()
To convert a string to int in C++, atoi() can also be used, atoi() method works similarly to the stoi( ) function; it also converts a string to an integer. But the difference is that only C-style strings such as character array and string literals are supported by atoi() , whereas stoi() supports both C and C++ style strings.
Parameters: The atoi() function accepts a pointer to a character array as an argument. Return value : The atoi() function returns an integer value. Header file:
Let’s understand with sample code: Code
Explanation:
- In the first string str1 = «42» , stoi(str1) converts all the integer values of str1 to int and stores them in num1 .
- In the second string str2 = «54 fifty four» ; stoi(str2) converts all the integer values of str2 till first non-integer value that is space » » to int and stores them in num2 .
- In the third-string str3 = «62 sixty-two 54″ ; stoi(str3) converts all the integer values of str1 till the first non-integer value that is space » » to int and stores them in num3 .
But let’s take a case when the first value is a non-integer value.
Explanation: If the starting character is a non-integer character, the atoi() function returns «0» . It doesn’t give any error message like stoi() on the output screen.
Using stringstream
To convert string to int C++, stringstream can also be used. A stringstream class is a stream class that allows you to read from a string by associating a string object with a stream (such as cin ). A numeric string is converted to an int type using the stringstream class.
Parameters : The stringstream object accepts a string as an arguement: Header files : and
Let’s understand with sample code: Code
Explanation: stringstream strm(str) ; is declaring a stringstream object on string str. strm >> num ; takes input from string stream and writes them to num.
But let’s take a case when the first value is a non-integer value.
Explanation: If the starting character is a non-integer character, the stringstream also returns «0» like atoi() . It doesn’t give any error message like stoi() on the output screen.
Difference between stoi() and atoi()
stoi() atoi Both C++ and C-style strings, such as character array and string literal, are supported by atoi(). Only C-style strings such as character array and string literal are supported by atoi(). Header file to be imported is Header file to be imported is If the starting character is a non-integer character, the stoi() function gives runtime error If the starting character is a non-integer character, the atoi() function returns 0. It doesn’t give any errors. Conclusion
- The string to int C++ can be converted using stoi, atoi, stringstream methods.
- To convert string to int C++, some header files have to be imported. Header files to be imported to convert string to int c++ using stoi() is , for atoi() is , and for stringstream and .
- If the starting character is a non-integer character, the stoi() function gives runtime error, whereas atoi() and stringstream return 0 , which doesn’t give any error.
Read More: