- 4 Ways of Converting String to Int in C++
- String to int in C++: the “modern” C++-style way using std::stoi()
- String to int in C++: the stream based C++-style way using string stream
- String to int in C++: the Boost way using Spirit.X3 parser
- String to int in C++: the C-style way using strtol()
- String to Int in C++ – How to Convert a String to an Integer Example
- Data types in C++
- How to declare and initialize int s in C++
- How to declare and initialize string s in C++
- How to convert a string to an integer
- How to convert a string to an int using the stoi() function
- How to convert a string to an int using the stringstream class
- Conclusion
- How to convert a string to an int in C++
- 1. Using the stringstream class
- 2. Using stoi()
- 3. Using atoi()
- String to int conversion in cpp
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
4 Ways of Converting String to Int in C++
It is common to convert a string ( std::string ) to integer (int) in C++ programs. Because of the long history of C++ which has several versions with extended libraries and supports almost all C standard library functions, there are many ways to convert a string to int in C++. This post introduces how to convert a string to an integer in C++ using C and C++ ways and libraries. If you would like to convert int to string, please check How to Convert Int to String in C++.
We can use the functions and classes provided by the C standard library and C++ standard library to convert string to int in C++.
String to int in C++: the “modern” C++-style way using std::stoi()
We can use the std::stoi() function from C++ standard library since C++11. The std::stoi() function is recommended to use if the development environment is not locked to the pre-C++11 standard.
Defined in header int stoi( const std::string& str, std::size_t* pos = 0, int base = 10 ); (1) (since C++11)
Discards any whitespace characters (as identified by calling isspace()) until the first non-whitespace character is found, then takes as many characters as possible to form a valid base-n (where n=base) integer number representation and converts them to an integer value.
std::out_of_range if the converted value would fall out of the range of the result type or if the underlying function (std::strtol or std::strtoll) sets errno to ERANGE.
One example C++ program to convert string to int using std::stoi() is as follows.
If the parsing fails, std::stoi() will raise exceptions.
String to int in C++: the stream based C++-style way using string stream
Use C++ standard library’s string stream std::istringstream which can parse the string as an input stream for various types. In this way, we convert the string to int. The sstream header contains the function/class declaration for the string stream library.
We should check std::istringstream::fail() function to check whether there is any error during parsing the string.
String to int in C++: the Boost way using Spirit.X3 parser
Boost has a header only library Spirit.X3 that implements a parser for C++. It is a powerful parser that can easily parse integers with its numeric parsers. For parsing integer, we can use the boost::spirit::x3::int_ parser.
One usage example is as follows.
#include #include int main(int argc, char* args[]) < namespace x3 = boost::spirit::x3; using x3::int_; std::string str("123"); // parse with boost spirit x3 int_ parser int value = 0; std::string::iterator strbegin = str.begin(); x3::parse(strbegin, str.end(), int_, value); std::cout
String to int in C++: the C-style way using strtol()
We can also use the C standard library function strtol (avoid atoi() which does not report errors) to convert string to int in C++.
#include long int strtol(const char *nptr, char **endptr, int base);
An example C++ code using the strtol() function is as follows.
#include #include #include int main() < std::string text; errno = 0; // pre set to 0 int number = (int)std::strtol(text.c_str(), nullptr, 10); if (errno == ERANGE) < // the number is too big/small // number = (int)LONG_MAX or (int)LONG_MIN std::cerr else if (errno) < // maybe EINVAL, E2BIG or EDOM // unable to convert to a number std::cerr // TODO: you need to check whether the long to int overflow too if neccessary std::cout
The errors are reported in the C-style way by setting the errno . We should check the errno for any errors.
String to Int in C++ – How to Convert a String to an Integer Example
Dionysia Lemonaki
When you're coding in C++, there will often be times when you'll want to convert one data type to a different one.
In this article you'll learn how to convert a string to an integer in C++ by seeing two of the most popular ways to do so.
Data types in C++
The C++ programming language has a few built-in data types:
- int , for integer (whole) numbers (for example 10, 150)
- double , for floating point numbers (for example 5.0, 4.5)
- char , for single characters (for example 'D', '!')
- string , for a sequence of characters (for example "Hello")
- bool , for boolean values (true or false)
C++ is a strongly typed programming language, meaning that when you create a variable you have to explicitely declare what type of value will be stored in it.
How to declare and initialize int s in C++
To declare an int variable in C++ you need to first write the data type of the variable – int in this case. This will let the compiler know what kind of values the variable can store and therefore what actions it can take.
Next, you need give the variable a name.
Lastly, don't forget the semicolon to end the statement!
You can then give the variable you created a value, like so:
Instead of doing these actions as separate steps, you can combine them by initializing the variable and finally printing the result:
// a header file that enables the use of functions for outputing information //e.g. cout or inputing information e.g. cin #include // a namespace statement; you won't have to use the std:: prefix using namespace std; int main() < // start of main function of the program int age = 28; // initialize a variable. //Initializing is providing the type,name and value of the varibale in one go. // output to the console: "My age is 28",using chaining, // end the main function
How to declare and initialize string s in C++
Strings are a collection of individual characters.
Declaring strings in C++ works very similarly to declaring and initializing int s, which you saw in the section above.
The C++ standard library provides a string class. In order to use the string data type, you'll have to include the header library at the top of your file, after #include .
After including that header file, you can also add using namespace std; which you saw earlier.
Among other things, after adding this line, you won't have to use std::string when creating a string variable – just string alone.
#include #include using namespace std; int main() < //declare a string variable string greeting; greeting = "Hello"; //the `=` is the assignment operator,assigning the value to the variable >
Or you can initialize a string variable and print it to the console:
#include #include using namespace std; int main() < //initialize a string variable string greeting = "Hello"; //output "Hello" to the console cout
How to convert a string to an integer
As mentioned earlier, C++ is a strongly typed language.
If you try to give a value that doesn't align with the data type, you'll get an error.
Also, converting a string to an integer is not as simple as using type casting, which you can use when converting double s to int s.
For example, you cannot do this:
#include #include using namespace std; int main()
The error after compiling will be:
hellp.cpp:9:10: error: no matching conversion for C-style cast from 'std::__1::string' (aka 'basic_string, allocator >') to 'int' num = (int) str; ^~~~~~~~~ /Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/string:875:5: note: candidate function operator __self_view() const _NOEXCEPT < return __self_view(data(), size()); >^ 1 error generated.
There are a few ways to convert a string to an int, and you'll see two of them mentioned in the sections that follow.
How to convert a string to an int using the stoi() function
One effective way to convert a string object into a numeral int is to use the stoi() function.
This method is commonly used for newer versions of C++, with is being introduced with C++11.
It takes as input a string value and returns as output the integer version of it.
#include #include using namespace std; int main() < // a string variable named str string str = "7"; //print to the console coutI am a string 7 I am an int 7
How to convert a string to an int using the stringstream class
The stringstream class is mostly used in earlier versions of C++. It works by performing inputs and outputs on strings.
To use it, you first have to include the sstream library at the top of your program by adding the line #include .
You then add the stringstream and create an stringstream object, which will hold the value of the string you want to convert to an int and will be used during the process of converting it to an int.
You use the extract the string from the string variable.
Lastly, you use the >> operator to input the newly converted int value to the int variable.
#include #include #include // this will allow you to use stringstream in your program using namespace std; int main() < //create a stringstream object, to input/output strings stringstream ss; // a variable named str, that is of string data type string str = "7"; // a variable named num, that is of int data type int num; //extract the string from the str variable (input the string in the stream) ss > num; //print to the consloe cout
Conclusion
And there you have it! You have seen two simple ways to convert a string to an integer in C++.
If you're looking to learn more about the C++ programming language, check out this 4-hour course on freeCodeCamp's YouTube channel.
Thanks for reading and happy learning 😊
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:
#include#includeusing namespace std;int main()// 3 string examples to be used for conversionconst char* str_example_1 = "100";const char* str_example_2 = "2.256";const char* str_example_3 = "200 Educative";// using stoi() on various kinds of inputsint int_1 = atoi(str_example_1);int int_2 = atoi(str_example_2);int int_3 = atoi(str_example_3);coutcoutcout>Learn in-demand tech skills in half the time
String to int conversion in cpp
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 weekLike/Subscribe us for latest updates or newsletter