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.
Your while condition is incorrect:
The loop never terminates and
ibecomes large (more than string length minus one) and when you access the string at that index you get runtime assertion.Change it to:
Or better use iterators.