C++;超出下标范围 我正在运行一个C++程序,它应该把字符串转换成十六进制。它会编译,但运行时我会出错,说:

C++;超出下标范围 我正在运行一个C++程序,它应该把字符串转换成十六进制。它会编译,但运行时我会出错,说:,c++,arrays,string,hex,C++,Arrays,String,Hex,调试断言失败!(哦,不!) Visual Studio2010\include\x字符串 第1440行 表达式:字符串下标超出范围 我没有选择放弃。。。它似乎转换了它,虽然到了错误的程度,所以我不确定发生了什么。我的代码很简单: #include <iostream> #include <iomanip> #include <string> using namespace std; int main() { string hello = "Hello

调试断言失败!(哦,不!)

Visual Studio2010\include\x字符串

第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;
}
#包括
#包括
#包括
使用名称空间std;
int main()
{
string hello=“hello World”;
int i=0;
while(hello.length())
{
cout
while(icout您没有从字符串中删除任何内容,因此
length()
将始终返回转换为
true
的相同数字

改为使用for循环:

for(int i = 0; i < hello.length(); ++i)
{
    cout << setfill('0') << setw(2) << hex << (unsigned int)hello[i];
}
for(int i=0;i当您的情况不正确时,不能

while(hello.length())
循环从不终止,
i
变大(大于字符串长度减1),当您访问该索引处的字符串时,您将得到运行时断言

将其更改为:

while(i < hello.length())
while(i

或者最好使用迭代器。

while循环中缺少条件

for(std::string::iterator it = hello.begin(); it != hello.end(); ++it)
{
    cout << setfill('0') << setw(2) << hex << *it;
}
 while(i < hello.length())
    {
        cout << setfill('0') << setw(2) << hex << (unsigned int)hello[i];
        ++i;
    }
while(icout我更喜欢for循环中的迭代器

for (std::string::const_iterator it = hello.begin(); it != hello.end(); ++it) {
    // String processing
}
或者,在C++11中:

for (char const c : hello) {
    // String processing
}
一般来说,我更喜欢使用迭代器在C++中访问任何可能的东西。这是更习惯的方式,它适用于所有类型的STL容器。例如,如果你想某天使用<代码> STD::DeQue>代码>或<代码> STD::列表< /C> >,迭代器仍然可以工作。< /P>
在另一个风格方面,我会避免C风格的强制转换。这就是你做的
(unsigned int)
。相反,使用
静态强制转换(*it)
。这传达了你的意图,只提供了你真正想要的施法能力。C样式的施法范围更广,但你只想在整数类型的大小之间进行转换。

哦,哇,为什么它会编译并给出如此奇怪的错误消息?(谢谢btw)@您好,因为编译器不应该查找运行时错误。请注意,如果在
while
表达式中有常量或局部变量,则会收到警告。但是函数调用会使编译器假设数据可能会更改。@Jesse谢谢:)有时我觉得我在与谁的速度更快进行竞争。。。。
for (char const c : hello) {
    // String processing
}