Convert Strings Into Numbers in C++

Convert strings into number in C++
Convert strings into number in C++

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.

STRING TO NUMBER CONVERSION:

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:

First option: sscanf()

#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.”

Second option: std::sto*()

#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 on C++11 compliant compilers.

Third option: sstreams

#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??

Fourth option: Boost’s lexical_cast

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.

Fifth option: Qt

#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

Program to convert string into number:-

#include<iostream>
#include<sstream>
using namespace std;
int main() {
string s = "999";
stringstream degree(s);
int x = 0;
degree >> x;
cout << "Value of x: " << x;
}

In the example above, we declare degree as the string stream object that acts as the intermediary and holds the value of the string. Then, by entering degree >> x, we extract the value out of the object and store it as integer x.

Finally, use the cout function to display the result. If you use the code above properly, your output should look like this:

Value of x: 999

Conclusions:

Summing up, the best solution is C++11 std::stoi() or, as a second option, the use of Qt libraries. All other solutions are discouraged or buggy.

NUMBER TO STRING CONVERSION:

Converting a number to a string takes two steps using string streams:

  • Outputting the value of the number to the stream
  • Getting the string with the contents of the stream

As with this conversion needs only output operation with the stream, an ostringstream (output string stream) can be used instead of the stream for both input and output (stringstream).

Here is an example that shows each step:

int Number = 123; // number to be converted to a string
string Result; // string which will contain the result
ostringstream convert; // stream used for the conversion
convert << Number; // insert the textual representation of 'Number' in the characters in the stream
Result = convert.str(); // set 'Result' to the contents of the stream
      // 'Result' now is equal to "123"
This operation can be shorten into a single line:
int Number = 123;
string String = static_cast( &(ostringstream() << Number) )->str();

Do not use the itoa or itof functions because they are non-standard and therefore not portable.

Use string streams:

#include <sstream> //include this to use string streams
#include<string>
int main()
{
int number = 1234;
std::ostringstream ostr; //output string stream
ostr << number; //use the string stream just like cout,
//except the stream prints not to stdout but to a string.
std::string theNumberString = ostr.str(); //the str() function of the stream
//returns the string.
//now theNumberString is "1234"
}
Note that you can use string streams also to convert floating-point numbers to string, and also to format the string as you wish, just like with cout

std::ostringstream ostr;
float f = 1.2;
int i = 3;
ostr << f << " + " i << " = " << f + i;
std::string s = ostr.str();
//now s is "1.2 + 3 = 4.2"
You can use stream manipulators, such as std::endl, std::hex and functions std::setw(), std::setprecision() etc. with string streams in exactly the same manner as with cout.

Do not confuse std::ostringstream with std::ostrstream. The latter is deprecated.

Use boost lexical cast, if you are not familiar with boost, it is a good idea to start with a small library like this lexical_cast. Although boost isn’t in C++ standard many libraries of boost get standardized eventually and boost is widely considered of the best C++ libraries.

The lexical cast uses streams underneath, so basically this option is the same as the previous one, just less verbose.

#include <boost/lexical_cast.hpp>
#include <string>
int main()
{
float f = 1.2;
int i = 42;
std::string sf = boost::lexical_cast(f); //sf is "1.2"
std::string si = boost::lexical_cast(i); //sf is "42"
}
numeric to string
string to_string(int val);
string to_string(unsigned val);
string to_string(long val);
string to_string(unsigned long val);
string to_string(long long val);
string to_string(unsigned long long val);
string to_string(float val);
string to_string(double val);
string to_string(long double val);

Program to convert Number into string:

#include <iostream>
#include <sstream>
using namespace std;
int main() {
int k;
cout<<"Enter an integer value"; cin>>k;
stringstream ss;
ss<>s;
cout<<"\n"<<"An integer value is : "<<k<<"\n";
cout<<"String representation of an integer value is : "<<s;
}

Output:
Enter an integer value 45
An integer value is: 45
A string representation of an integer value is 45

In the above example, we created the k variable, and want to convert the value of k into a string value. We have used the stringstream class, which is used to convert the k integer value into a string value. We can also achieve vice versa, i.e., conversion of string into an integer value is also possible through the use of stringstream class only.

These are more straightforward, you pass the appropriate numeric type and you get a string back. These functions fall back to a default mantissa precision that is likely not the maximum precision. If more precision is required for your application it’s also best to go back to other string formatting procedures.

There are also similar functions defined that are named to_wstring, these will return a std::wstring.

To explore more about C++ programming and also read about how to reserve a string in C and C++, click here.

By Akhil Sharma

Exit mobile version