Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Methods to Convert String to Integer in C++
2.1.
Example Code
2.2.
String to int Conversion Using sscanf() Function
2.2.1.
Syntax
2.2.2.
Parameters
2.2.3.
Return Value
2.2.4.
Code
2.3.
String to int Conversion Using std::sto*() Function
2.3.1.
Syntax 
2.3.2.
Parameters
2.3.3.
Return Value
2.3.4.
Code
2.4.
String to int Conversion Using Streams Function
2.4.1.
Syntax 
2.4.2.
Parameters
2.4.3.
Return Value
2.4.4.
Code
2.5.
String to int Conversion Using Boost’s lexical_cast Function
2.5.1.
Syntax 
2.5.2.
Parameters
2.5.3.
Return Value
2.5.4.
Code
2.6.
String to int Conversion Using  Qt Function
2.6.1.
Syntax
2.6.2.
Parameters
2.6.3.
Return Value
2.6.4.
Code
3.
Program to convert string into number
3.1.
C++
4.
NUMBER TO STRING CONVERSION
4.1.
Use string streams
5.
Program to convert Number into string
5.1.
C++
6.
Frequently Asked Questions
6.1.
Can we convert a string into an integer?
6.2.
Which function converts a string to an integer?
6.3.
What happens if the string is not a valid integer when using std::stoi?
6.4.
What happens if the string is not a valid floating-point number when using std::stof or std::stod?
6.5.
What are some common algorithms for graph traversal?
7.
Conclusion
Last Updated: Aug 3, 2024
Medium

Convert Strings Into Numbers in C++

Author Nilesh Kumar
0 upvote

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.

Convert Strings Into Numbers in C++

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.

Program to convert string into number

  • C++

C++

#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;
}
You can also try this code with Online C++ Compiler
Run Code

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

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

  • C++

C++

#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;
}
You can also try this code with Online C++ Compiler
Run Code

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.

Check out this article - C++ String Concatenation

 Also Read - Strong number in c

Frequently Asked Questions

Can we convert a string into an integer?

Yes, a string can be converted into an integer using various methods available in different programming languages, such as stoi in C++.

Which function converts a string to an integer?

In C++, the stoi function converts a string to an integer. In Qt, QString::toInt() performs this conversion.

What happens if the string is not a valid integer when using std::stoi?

If the string is not a valid integer, std::stoi will throw an std::invalid_argument exception.

What happens if the string is not a valid floating-point number when using std::stof or std::stod?

If the string is not a valid floating-point number, std::stof or std::stod will throw an std::invalid_argument exception.

What are some common algorithms for graph traversal?

There are two main algorithms for graph traversal: depth-first search (DFS) and breadth-first search (BFS). DFS is a recursive algorithm that explores as far as possible along each branch before backtracking, while BFS explores the graph layer by layer, visiting all the neighbors of a node before moving on to the next level.

Conclusion

This article discussed Convert Strings Into Numbers in C++ and a program to convert strings into numbers. You can also refer

Recommended problems -

To learn more about DSA, competitive coding, and many more knowledgeable topics, please look into the guided paths on Code360. Also, you can enroll in our courses and check out the mock test and problems available to you. Please check out our interview experiences and interview bundle for placement preparations.

Happy Learning!

Live masterclass