In C++, one of the most common operations you will need to perform when working with strings is converting them to numeric values, or vice versa. Whether you are processing user input, reading data from a file, or manipulating numerical values in a string format, the ability to convert between strings and numeric types is essential for smooth data handling.
This post explores the various methods available in C++ for converting strings to numbers, including using functions like stoi()
, stol()
, stof()
, stod()
, and converting numbers back to strings with to_string()
. We’ll also cover how to handle invalid conversions using exception handling mechanisms, specifically the try-catch block, and provide examples demonstrating how to read numbers as strings from input.
1. Introduction to String to Number Conversion
In many programming scenarios, data is represented as strings, but you may need to perform arithmetic operations or comparisons with numbers. This is where string-to-number conversion comes into play. C++ offers various ways to convert strings to numeric types such as int
, long
, float
, double
, and more. Each method has specific use cases and benefits.
The two primary tasks involved in string and number conversion are:
- Converting strings to numbers for performing arithmetic or logical operations.
- Converting numbers to strings for display or further processing.
This post will cover both conversions in detail, focusing on:
- Converting strings to integers, longs, floats, and doubles.
- Converting numbers to strings.
- Handling invalid conversions using C++ exception handling.
2. Converting Strings to Numbers
C++ provides built-in functions for converting strings to numeric types. These functions handle the most common numeric types you will work with: integers, long integers, floats, and doubles.
2.1 Using stoi()
for Integer Conversion
The function stoi()
(string to integer) is used to convert a string to an integer. It parses the string and returns the integer value.
Syntax
int stoi(const string& str, size_t* pos = 0, int base = 10);
- str: The string to be converted.
- pos (optional): A pointer to a variable that stores the index of the first character not converted.
- base (optional): The base for conversion (default is 10 for decimal).
Example: Converting String to Integer
#include <iostream>
#include <string>
using namespace std;
int main() {
string numStr = "12345";
int num = stoi(numStr);
cout << "Converted number: " << num << endl;
return 0;
}
Output
Converted number: 12345
Explanation
In the example above, the string "12345"
is successfully converted to the integer 12345
.
2.2 Using stol()
for Long Integer Conversion
The stol()
function is used to convert a string to a long integer. It works similarly to stoi()
, but returns a long
value instead of an int
.
Syntax
long stol(const string& str, size_t* pos = 0, int base = 10);
- str: The string to be converted.
- pos (optional): A pointer to the index of the first character not converted.
- base (optional): The base for conversion (default is 10 for decimal).
Example: Converting String to Long Integer
#include <iostream>
#include <string>
using namespace std;
int main() {
string numStr = "9876543210";
long num = stol(numStr);
cout << "Converted number: " << num << endl;
return 0;
}
Output
Converted number: 9876543210
Explanation
The string "9876543210"
is successfully converted into the long integer 9876543210
.
2.3 Using stof()
for Float Conversion
The stof()
function converts a string to a float. This is useful when you need to convert a string containing a decimal number.
Syntax
float stof(const string& str, size_t* pos = 0);
- str: The string to be converted.
- pos (optional): A pointer to the index of the first character not converted.
Example: Converting String to Float
#include <iostream>
#include <string>
using namespace std;
int main() {
string numStr = "3.14159";
float num = stof(numStr);
cout << "Converted number: " << num << endl;
return 0;
}
Output
Converted number: 3.14159
Explanation
Here, the string "3.14159"
is converted to the floating-point number 3.14159
.
2.4 Using stod()
for Double Conversion
The stod()
function is used for converting a string to a double. A double
provides higher precision than a float
.
Syntax
double stod(const string& str, size_t* pos = 0);
- str: The string to be converted.
- pos (optional): A pointer to the index of the first character not converted.
Example: Converting String to Double
#include <iostream>
#include <string>
using namespace std;
int main() {
string numStr = "2.718281828459045";
double num = stod(numStr);
cout << "Converted number: " << num << endl;
return 0;
}
Output
Converted number: 2.71828
Explanation
In this example, the string "2.718281828459045"
is converted into the double value 2.71828
.
3. Converting Numbers to Strings
In C++, you can easily convert numbers to strings using the to_string()
function. This function allows you to convert integers, long integers, floats, and doubles to their string representations.
Syntax
string to_string(val);
- val: The numeric value to be converted.
Example: Converting Integer to String
#include <iostream>
#include <string>
using namespace std;
int main() {
int num = 123;
string numStr = to_string(num);
cout << "Converted string: " << numStr << endl;
return 0;
}
Output
Converted string: 123
Explanation
The integer 123
is converted to the string "123"
.
Example: Converting Double to String
#include <iostream>
#include <string>
using namespace std;
int main() {
double num = 3.14159;
string numStr = to_string(num);
cout << "Converted string: " << numStr << endl;
return 0;
}
Output
Converted string: 3.141590
Explanation
Here, the double 3.14159
is converted to the string "3.141590"
. Notice that the to_string()
function may add extra precision to floating-point numbers.
4. Handling Invalid Conversions with Try-Catch
One of the most important aspects of string-to-number conversion is handling invalid input. If a string cannot be converted to a number, the conversion functions throw an exception.
C++ provides the invalid_argument
and out_of_range
exceptions to handle errors during conversion.
4.1 Handling Invalid Input
If the string does not contain a valid representation of a number, stoi()
, stol()
, stof()
, and stod()
will throw an invalid_argument
exception.
4.2 Handling Out of Range Errors
If the number in the string exceeds the range of the destination data type, an out_of_range
exception is thrown.
Example: Handling Conversion Errors
#include <iostream>
#include <string>
#include <stdexcept>
using namespace std;
int main() {
string str = "abc123"; // Invalid number
try {
int num = stoi(str);
cout << "Converted number: " << num << endl;
} catch (invalid_argument& e) {
cout << "Error: Invalid argument - " << e.what() << endl;
} catch (out_of_range& e) {
cout << "Error: Out of range - " << e.what() << endl;
}
return 0;
}
Output
Error: Invalid argument - stoi: no conversion
Explanation
In this example, the string "abc123"
is invalid for conversion, so an invalid_argument
exception is caught and the error message is displayed.
5. Practical Examples of Reading Numbers as Strings
Sometimes you might want to read numbers as strings from input, especially when dealing with user inputs where the input may not always be a valid number. Here’s how you can handle such cases:
Example: Reading Numbers as Strings
#include <iostream>
#include <string>
using namespace std;
int main() {
string input;
cout << "Enter a number: ";
cin >> input;
try {
int num = stoi(input);
cout << "Converted number: " << num << endl;
} catch (invalid_argument& e) {
cout << "Invalid input! Please enter a valid number." << endl;
}
return 0;
}
Explanation
- The program asks the user to input a number as a string.
- The string is then converted to an integer using
stoi()
. - If the input is invalid (e.g., a non-numeric string), an error message is displayed using exception handling.
Leave a Reply