3

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?

YSC
  • 38,212
  • 9
  • 96
  • 149
M. Meek
  • 33
  • 7
  • Possible duplicate of [Integer to hex string in C++](https://stackoverflow.com/questions/5100718/integer-to-hex-string-in-c) – Nico Jul 05 '18 at 11:57
  • `hex` has size zero. All usages of `hex[i]` give undefined behaviour. – Peter Jul 05 '18 at 11:59

1 Answers1

4

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();
}
YSC
  • 38,212
  • 9
  • 96
  • 149
  • Thank you for the quick response! That fixed the issue that I had with the code, however, I've run into another issue where if I try to cout< – M. Meek Jul 05 '18 at 12:03
  • @M.Meek Please ask only one question per question. You asked why you get an exception, and it was answered. If you want to ask about getting invalid output, either step through the code with a debugger, to figure that out, or ask a different question, having all relevant information. – Algirdas Preidžius Jul 05 '18 at 12:17