C++ Out of Subscript Range

arrays, c++, hex, string

Solution

Your while condition is incorrect:

while(hello.length())

The loop never terminates and `i` becomes large (more than string length minus one) and when you access the string at that index you get runtime assertion.

Change it to:

while(i < hello.length())

Or better use iterators.

Problem

I'm running a C++ Program that is supposed to convert string to hexadecimals. It compiles but errors out of me at runtime saying: Debug Assertion Failed! (Oh no!) Visual Studio2010\include\xstring Line 1440 Expression: string subscript out of range And I have no choice to abort... It seems like it converts it though up to the point of error so I'm not sure what's going on. My code is simple: ``` #include <iostream> #include <iomanip> #include <string> using namespace std; int main() { string hello = "Hello World"; int i = 0; while(hello.length()) { cout << setfill('0') << setw(2) << hex << (unsigned int)hello[i]; i++; } return 0; } ``` What this program should do is convert each letter to hexadecimal - char by char.

Original source