Converting a string to int can be useful in any size of C++ application. There
are several ways that can be used to convert a string to int in C++. Depending
on your scenario you can choose the best method. However, most widely used
method is std::stoi for C++11 or above for development.
- Using std::stoi (After C++11)
- Using atoi
- Using sstream
- Using sscanf
- Using strtol (Not discussed in this article)
Using std::stoi (After C++11)
This method can be used after C++11 to convert a string to int. Make sure to
include <string> to use std::stoi function.
Most of the times we only pass a single parameter to this method which is the
string. But this function can be used for more advanced use cases as well.
Common use case:
Other use cases:
Please keep in mind that this function can throw exceptions. Depending on the
programme you will need to handle the exceptions.
Refer
this article
for information about std::stoi.
Using atoi
This is a legacy c-style method which only takes a c-string as the only
argument. This method does not throw any exceptions. If a conversion is
not performed this function will return 0. Make sure to include
<stdlib.h> to use atoi funtion.
Using sstream (String Streams)
String streams can be used convert a string to int and many other types. Don't
forget to include when using string streams.
Depending on your programme if you are not sure the value of the string is not
an integer you will need to do error handling.
Using sscanf
int sscanf ( const char * s, const char * format, ...);
This method returns the number of arguments in argument list successfully
filed. So if you expect only a single number will be there in the string it
should return 1. You can use that information for error handling.