This Tutorial Covers the C++ String Conversion Functions that can be used to Convert the string to int & double and int to a string etc.:
It is common to convert string to numbers like integer and double when we are developing C++ applications.
This topic covers the functions that can be used to effectively convert the strings to int & double and numeric values to a string.
=> Read Through The Popular C++ Training Series Here.
Table of Contents:
C++ String Conversion Functions
When we program applications using C++, it becomes necessary to convert data from one type to another. The conversion of data should be such that no data is lost at all when we convert the existing data to a new type. This is especially true when we convert string data to numbers and vice-versa.
In this tutorial, we will discuss the various functions to convert std:: string object to numeric data types including integer and double.
Convert String To Numeric Types In C++
In general, there are two common methods to convert string to numbers in C++.
- Using stoi and atoi functions that replicate for all the numeric data types.
- Using stringstream class.
Let us discuss each method in detail.
Using stoi And atoi Functions
std:: string class supports various functions to convert string to integer, long, double, float, etc. The conversion functions supported by std:: string are tabularized as follows:
Function | Description |
---|---|
stoi stol stoll | Converts string to integer (including long and long long types). |
atoi atol atoll | Converts byte string to integer (including long and long long types). |
stod stof stold | Converts byte string to floating point values (including float, double and long double types). |
stoul stoull | Converts byte string to unsigned integer (including unsigned long and unsigned long long types). |
Note: Except for the functions to convert byte string (atoi), all the other conversion functions are present from C++11 onwards. Now we will discuss the conversion functions to convert string to int and string to double.
String to int Using stoi() and atoi()
stoi()
Function Prototype: stoi( const std::string& str, std::size_t* pos = 0, int base = 10 );
Parameter(s):
str=> String to convert
pos=> Address of an integer to store number of chars processed; default = 0
base=> The number base; default=0
Return Value: Integer equivalent to string specified.
Exceptions: std::invalid_argument=>If no conversion can be performed.
Std::out_of_range=>If converted value is out of range of the range of result type.
Description: The function stoi () takes a string as an argument and returns an integer value. It will throw an exception if the converted value is out of range or if the conversion cannot be performed.
Let’s take a programming example to better understand this function.
#include <iostream> #include <string> using namespace std; int main() { string mystr1 = "53"; string mystr2 = "3.142"; string mystr3 = "31477 with char"; int strint1 = stoi(mystr1); int strint2 = stoi(mystr2); int strint3 = stoi(mystr3); cout << "stoi(\"" << mystr1 << "\") is " << strint1 << '\n'; cout << "stoi(\"" << mystr2 << "\") is " << strint2 << '\n'; cout << "stoi(\"" << mystr3 << "\") is " << strint3 << '\n'; }
Output:
stoi(“53”) is 53
stoi(“3.142”) is 3
stoi(“31477 with char”) is 31477
In the above program, we have used stoi function with three different strings. Note that while converting the string data to an integer value, the function discards the white spaces or any other characters.
Hence in the case of mystr2 (3.142), the function discarded everything after the decimal point. Similarly, in the case of mystr3 (“31477 with char”), only the number was taken into consideration. Other contents of the string were discarded.
atoi()
Function Prototype: int atoi( const char *str );
Parameter(s): str=> Pointer to null-terminated byte string.
Return Value:
Success=> Integer value corresponding to argument str.
Failure=> Undefined if the converted value is out of range.
0=> If no conversion can be performed.
Description: This function converts a byte string to an integer value. Function atoi () discards any whitespaces until a non-whitespace character is encountered and then takes the characters one by one to form a valid integer number representation and converts it to an integer.
Example of atoi Function
#include <iostream> #include <cstdlib> using namespace std; int main() { const char *mystr1 = "24"; const char *mystr2 = "3.142"; const char *mystr3 = "23446 with char"; const char *mystr4 = "words with 3"; int mynum1 = atoi(mystr1); int mynum2 = atoi(mystr2); int mynum3 = atoi(mystr3); int mynum4 = atoi(mystr4); cout << "atoi(\"" << mystr1 << "\") is " << mynum1 << '\n'; cout << "atoi(\"" << mystr2 << "\") is " << mynum2 << '\n'; cout << "atoi(\"" << mystr3 << "\") is " << mynum3 << '\n'; cout << "atoi(\"" << mystr4 << "\") is " << mynum4 << '\n'; }
Output:
atoi(“24”) is 24
atoi(“3.142”) is 3
atoi(“23446 with char”) is 23446
atoi(“words with 3”) is 0
As shown in the above program, the atoi function takes a byte string as an argument and converts it to an integer value. The white spaces or any other characters are discarded. If the converted value is out of range then 0 is returned.
String to double Using stod()
Function Prototype: stod( const std::string& str, std::size_t* pos = 0 );
Parameter(s):
str=> String to convert
pos=> Address of an integer to store the number of chars processed; default = 0
Return Value: Double value equivalent to the string specified.
Exceptions:
std::invalid_argument=>If no conversion can be performed.
std::out_of_range=>If converted value is out of range of the range of result type.
Description: This function converts a string to a floating-point value. Function stod () discards any whitespaces until a non-whitespace character is encountered and then takes the characters one by one to form a valid floating-point number representation and converts it to floating-point.
Let’s see an example demonstrating this function.
#include <iostream> #include <cstdlib> using namespace std; int main() { const char *mystr1 = "24"; const char *mystr2 = "3.142"; const char *mystr3 = "23446 with char"; double mynum1 = stod(mystr1); double mynum2 = stod(mystr2); double mynum3 = stod(mystr3); cout << "stod(\"" << mystr1 << "\") is " << mynum1 << '\n'; cout << "stod(\"" << mystr2 << "\") is " << mynum2 << '\n'; cout << "stod(\"" << mystr3 << "\") is " << mynum3 << '\n'; }
Output:
stod(“24”) is 24
stod(“3.142”) is 3.142
stod(“23446 with char”) is 23446
The above program demonstrates the usage of the “stod” function. The output indicates the converted double values of the specified strings.
Using stringstream Class
Using stringstream class is the easiest way to convert string values to numeric values.
We will be learning the stringstream class in detail in our subsequent tutorials. Given below is a C++ program that demonstrates the conversion of string to numeric values.
#include <iostream> #include <sstream> using namespace std; int main() { string str = "2508"; stringstream sstream(str); int num = 0; sstream >> num; double dNum=0.0; string doublestr = "3.142"; stringstream dstream(doublestr); dstream >>dNum; cout << "Value of num : " << num<<endl; cout << "Value of dNum : " << dNum; return 0; }
Output:
Value of num : 2508
Value of dNum : 3.142
In the above program, we see that we have declared a string object. Then we declare a stringstream object and pass the string to this object so that the string is converted to a stringstream object. Then this stringstream object is passed to an integer value using ‘>>’ operator that converts the stringstream object to an integer.
Similarly, we have also converted the string into double. So as long as “>>” operator supports the data type, we can convert a string into any data type using a stringstream object.
Convert int To string In C++
We can also convert numeric values to string values. There are two methods of converting numeric values to string values and we will discuss those below.
Using to_string() Function
Function Prototype: std::string to_string( type value );
Parameter(s): value=> Numeric value to convert
Return Value: String value holding the converted value.
Exception: may throw std::bad_alloc
Description: This function to_string () converts the numeric value passed as an argument to string type and returns the string.
Let’s see an example of this function using a C++ program.
#include<iostream> #include<string> // used for string and to_string() using namespace std; int main() { int int_val = 20; float flt_val = 30.50; string str_int = to_string(int_val); string str_float = to_string(flt_val); cout << "The string representation of integer : "; cout << str_int << endl; cout << "The string representation of float : "; cout << str_float << endl; return 0; }
Output:
The string representation of integer : 20 The string representation of float : 30.500000
Here we have two variables, each of type integer and float. Then we call the to_string method twice with integer and float argument and convert both the values into string values. Finally, we display the converted values.
Note that converting the floating-point value to the string may give unexpected results as the number of significant digits may be zero with the to_string method.
Using stringstream Class
Using stringstream class, the stringstream first declares a stream object that inserts a numeric value as a stream into the object. It then uses the “str()” function to internally convert a numeric value to string.
Example:
#include<iostream> #include <sstream> #include <string> using namespace std; int main() { int num = 26082019; double num_d = 3.142; ostringstream mystr; ostringstream my_dstr; mystr << num; string resultstr = mystr.str(); my_dstr << num_d; string d_str = my_dstr.str(); cout << "The string formed from integer is : "; cout << resultstr << endl; cout << "The string formed from double is : "; cout << d_str << endl; return 0; } #include<iostream> #include <sstream> #include <string> using namespace std; int main() { int num = 26082019; double num_d = 3.142; ostringstream mystr; ostringstream my_dstr; mystr << num; string resultstr = mystr.str(); my_dstr << num_d; string d_str = my_dstr.str(); cout << "The string formed from integer is : "; cout << resultstr << endl; cout << "The string formed from double is : "; cout << d_str << endl; return 0; }
Output:
The string formed from integer is: 26082019
The string formed from double is: 3.142
In this listing, we have defined an integer and a double value. Then we have the ostringstream object using which we covert the numeric value to the stringstream object. This is using the ‘<<’ operator. Next, we use the str() method on a stringstream object to convert it to a string.
Conclusion
In this tutorial, we discussed conversion functions that convert a string to numeric types and numeric types back to a string. We have seen the functions and examples of stoi (), stod (), atoi (), to_string () function in detail. We also discussed some of the stringstream class functions and methods that help us do the mentioned conversions.
Recommended reading =>> Convert String to Integer in Java and Methods to convert Int to String in Java
In our next tutorial, we will learn conversion functions for character data types.
=> Check The In-Depth C++ Training Tutorials Here.