C++超出下标范围

How*_*Gee 3 c++ arrays string hex

我正在运行一个C++程序,它应该将字符串转换为十六进制.它编译但在运行时我的错误说:

调试断言失败!(不好了!)

Visual Studio2010\include\xstring

1440行

表达式:字符串下标超出范围

我没有选择中止...似乎它将它转换为错误点,所以我不确定发生了什么.我的代码很简单:

#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;
}
Run Code Online (Sandbox Code Playgroud)

这个程序应该做的是将每个字母转换为十六进制 - char by char.

Pub*_*bby 6

您没有从字符串中删除任何内容,因此length()将始终返回转换为的相同数字true.

改为使用for循环:

for(int i = 0; i < hello.length(); ++i)
{
    cout << setfill('0') << setw(2) << hex << (unsigned int)hello[i];
}
Run Code Online (Sandbox Code Playgroud)

甚至更好,使用迭代器.

for(std::string::iterator it = hello.begin(); it != hello.end(); ++it)
{
    cout << setfill('0') << setw(2) << hex << *it;
}
Run Code Online (Sandbox Code Playgroud)