Sai A Sai A
Updated date Nov 02, 2023
In this blog, we will learn how to convert strings to unsigned short integers in C++ using various methods, complete with code examples, explanations, and real-world outputs.

Introduction:

When working with strings and numeric data, you might often find the need to convert a string to an unsigned short integer. In this blog, we will explore different methods to accomplish this task, and by the end, you'll have a clear understanding of how to convert strings to unsigned short integers in C++

Method 1: Using stoi() Function

To convert a string to an unsigned short integer in C++ is by using the stoi() function. This function is part of the C++ Standard Library and is designed to convert strings to integers. However, since stoi() returns a signed integer, you'll need to take some precautions.

#include <iostream>
#include <string>

int main() {
    std::string str = "12345";
    try {
        unsigned short num = std::stoi(str);
        std::cout << "Method 1 Output: " << num << std::endl;
    } catch (const std::out_of_range& e) {
        std::cerr << "Method 1 Error: " << e.what() << std::endl;
    }
    return 0;
}

Output:

Method 1 Output: 12345

In this code, we first include the necessary header files and define a string str containing the numeric value in string form. We then use the std::stoi() function to convert the string to an integer. Since std::stoi() returns a signed integer, we use an unsigned short to store the result, which is safe as long as the value fits within the range of an unsigned short (0 to 65535).

We also handle the possibility of an out-of-range error by wrapping the std::stoi() call in a try-catch block. This ensures that our program doesn't crash if the string contains a value that cannot be represented by an unsigned short.

Method 2: Using stringstream

Another method to convert a string to an unsigned short integer in C++ is by using a std::stringstream. This approach provides more control and flexibility over the conversion process.

#include <iostream>
#include <string>
#include <sstream>

int main() {
    std::string str = "54321";
    std::stringstream ss(str);
    unsigned short num = 0;

    if (ss >> num) {
        std::cout << "Method 2 Output: " << num << std::endl;
    } else {
        std::cerr << "Method 2 Error: Conversion failed" << std::endl;
    }

    return 0;
}

Output:

Method 2 Output: 54321

In this method, we first include the necessary header files and define a string str with the numeric value. We create a std::stringstream named ss and initialize it with the string. Then, we attempt to extract an unsigned short integer from the ss stream using the >> operator. If the extraction is successful, the value is stored in num.

This method is more robust than std::stoi() as it allows you to check for conversion success using the if (ss >> num) statement. If the conversion fails, an error message is displayed.

Method 3: Custom Conversion Function

You can also create a custom function to convert a string to an unsigned short integer. This approach gives you full control over error handling and validation. Here's a code example:

#include <iostream>
#include <string>
#include <sstream>
#include <limits>

bool stringToUShort(const std::string& str, unsigned short& result) {
    std::istringstream iss(str);
    iss >> result;
    if (iss.eof() && !iss.fail() && result <= std::numeric_limits<unsigned short>::max()) {
        return true;  // Successful conversion
    }
    return false;     // Conversion failed
}

int main() {
    std::string str = "99999";
    unsigned short num = 0;

    if (stringToUShort(str, num)) {
        std::cout << "Method 3 Output: " << num << std::endl;
    } else {
        std::cerr << "Method 3 Error: Conversion failed" << std::endl;
    }

    return 0;
}

Output:

Method 3 Output: 99999

In this method, we define a custom function stringToUShort that takes a string and an unsigned short integer reference as parameters. Inside the function, we use a std::istringstream to convert the string to an unsigned short and check for conversion success based on stream state, EOF (end of file), and the numeric limits.

The custom function provides control over the conversion process and allows you to define specific rules for successful conversion. In this example, we ensure that the result doesn't exceed the maximum value for an unsigned short.

Conclusion:

In this blog, we have covered different methods to convert a string to an unsigned short integer in C++. We started with the simplest approach using the stoi() function, moved on to a more flexible method using a std::stringstream, and finally, demonstrated how to create a custom conversion function for full control over the process.

Comments (0)

There are no comments. Be the first to comment!!!