M. Meek
M. Meek

Reputation: 33

C++ Decimal to Hexadecimal (String Subscript out of Range)

I ran into an issue when I was trying create a code that would convert a decimal to a hexadecimal string. This issue that I'm having is the "string subscript out of range" error. I can't seem to find out where the string conflicts with the range, therefore, I have come here to ask for your help to find out what is causing the error!

This is the code

int i;
int temp;
string hex;
long totalDecimal;
cin >> totalDecimal;

for (i = 0; totalDecimal != 0; i++)
{
    temp = totalDecimal % 16;

    if (temp < 10)
    {
        hex[i] = temp + 48;
    }
    else
    {
        hex[i] = temp + 55;
    }

    totalDecimal = totalDecimal / 16;
}

cout << hex;
return 0;

How to fix it?

Upvotes: 3

Views: 87

Answers (1)

YSC
YSC

Reputation: 40110

You are accessing characters inside hex which does not exist, since hexis empty:

hex[i] = temp + 48;

Reading the documentation of std::string::operator[]:

reference       operator[]( size_type pos );

Returns a reference to the character at specified location pos. No bounds checking is performed. If pos > size(), the behavior is undefined.

You need to use push_back or operator+= to append character at the end of an std::string:

hex += temp + 48;

A better way to convert integers to an hexadecimal representation would be, in C++, to use std::stringstream and std::hex:

#include <string>
#include <sstream>
#include <iomanip>
std::string to_hex(int i)
{
    std::stringstream ss;
    ss << std::hex << i;
    return ss.str();
}

Upvotes: 4

Related Questions