Introduction
There are many times where we want to convert the numbers into strings and strings to numbers in C++. Here we are giving some methods by which you can do that easily. It helps basically when you code for placement or for competitive programming.
Methods to Convert String to Integer in C++
We can solve this problem by using the atoi() function. This function takes a string as input and converts it into integer data. The atoi() function is present in the <cstdlib> library.
Example Code
#include<iostream>
#include<cstdlib>
using namespace std;
main() {
int n;
char num_string[20] = "1234";
n = atoi(num_string);
cout << n;
}
The possible options are described below:
String to int Conversion Using sscanf() Function
Syntax
int sscanf(const char *str, const char *format, ...);
Parameters
- str: The input string from which to read data.
- format: A format specifier string that determines how the input should be parsed (e.g., %d for integers).
- ...: Pointers to variables where the converted values will be stored.
Return Value
The return value of sscanf() is the number of input items successfully matched and assigned. If no conversions were performed, it returns 0. If an error occurs, it returns EOF.
Code
#include<cstdio>
#include<string>
int i;
float f;
double d;
std::string str;
// string -> integer
if(sscanf(str.c_str(), "%d", &i) != 1)
// error management
// string -> float
if(sscanf(str.c_str(), "%f", &f) != 1)
// error management
// string -> double
if(sscanf(str.c_str(), "%lf", &d) != 1)
// error management
This is an error (also shown by cppcheck) because “scanf without field width limits can crash with huge input data on some versions of libc.”
Explanation: The sscanf() function in C is used to read formatted input from a string, allowing for conversion of strings to integers and other data types.
String to int Conversion Using std::sto*() Function
Syntax
int std::stoi(const std::string &str, std::size_t *pos = nullptr, int base = 10);
Parameters
- str: The input string to be converted to an integer.
- pos: (Optional) A pointer to a variable that will store the index of the first character not processed. If not needed, it can be set to nullptr.
- base: (Optional) The numerical base to use for conversion (default is 10). It can be 0 (auto-detect), 2, 8, 10, or 16.
Return Value
Returns the converted integer. If conversion fails, a std::invalid_argument exception is thrown. If the result is out of range, a std::out_of_range exception is thrown.
Code
#include<iostream>
#include<string>
int i;
float f;
double d;
std::string str;
try {
// string -> integer
int i = std::stoi(str);
// string -> float
float f = std::stof(str);
// string -> double
double d = std::stod(str);
} catch (…) {
// error management
}
This solution is short and elegant, but it is available only on C+11 compliant compilers.
Explanation: The std::stoi() function in C++ is used to convert a string to an integer.
String to int Conversion Using Streams Function
Syntax
#include <sstream>
std::istringstream iss(str);
iss >> num;
Parameters
- str: The input string containing the integer representation.
- iss: An instance of std::istringstream that is used to read from the string.
Return Value
The return value of the stream extraction operator (>>) is the stream itself, which can be checked for success or failure. If the conversion is successful, the integer is stored in the specified variable.
Code
#include<iostream>
#include<sstream>
int i;
float f;
double d;
std::string str;
// string -> integer
std::istringstream ( str ) >> i;
// string -> float
std::istringstream ( str ) >> f;
// string -> double
std::istringstream ( str ) >> d;
// error management??
Explanation: You can convert a string to an integer in C++ using streams, specifically std::istringstream.
String to int Conversion Using Boost’s lexical_cast Function
Syntax
#include <boost/lexical_cast.hpp>
int boost::lexical_cast<int>(const std::string &str);
Parameters
- str: The input string containing the integer representation to be converted.
Return Value
Returns the converted integer. If the conversion fails (e.g., the string is not a valid integer), it throws a boost::bad_lexical_cast exception.
Code
#include<boost/lexical_cast.hpp>
#include<string>
std::string str;
try {
int i = boost::lexical_cast( str.c_str());
float f = boost::lexical_cast( str.c_str());
double d = boost::lexical_cast( str.c_str());
} catch( boost::bad_lexical_cast const& ) {
// Error management
}
However, this is just a wrapper of sstream, and the documentation suggests to use sstream for better error management.
Explanation: Boost's lexical_cast is a convenient way to convert between types, including converting a string to an integer.
String to int Conversion Using Qt Function
Syntax
In Qt, the QString class provides a method called toInt() for converting a string to an integer. The syntax is as follows:
int QString::toInt(bool *ok = nullptr, int base = 10) const;
Parameters
- *bool ok: (Optional) A pointer to a boolean variable that indicates whether the conversion was successful. If the conversion fails, ok is set to false.
- int base: (Optional) The numerical base to be used for the conversion. The default value is 10 (decimal).
Return Value
The toInt() function returns the integer representation of the string. If the conversion fails, it returns 0. If an ok pointer is provided, the function also sets the boolean value pointed to by ok to true or false based on the success of the conversion.
Code
#include<QString>
#include<string>
bool ok;
std::string;
int i = QString::fromStdString(str).toInt(&ok);
if (!ok)
// Error management
float f = QString::fromStdString(str).toFloat(&ok);
if (!ok)
// Error management
double d = QString::fromStdString(str).toDouble(&ok);
if (!ok)
// Error management
Explanation: This code snippet demonstrates how to convert a std::string to int, float, and double using Qt's QString class. It uses the fromStdString method to convert the std::string to a QString and then calls toInt, toFloat, and toDouble methods with a bool pointer to check the success of each conversion. The if (!ok) blocks are placeholders for error management.