C++超出下标范围

C++ Out of Subscript Range

本文关键字:范围 下标 C++      更新时间:2023-10-16

我正在运行一个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;
}

该程序应该做的是将每个字母转换为十六进制 - 逐个字符。

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

请改用 for 循环:

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

或者更好的是,使用迭代器。

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

您的 while 条件不正确:

while(hello.length())

循环永远不会终止,i变得很大(超过字符串长度减去 1),当您访问该索引处的字符串时,您将获得运行时断言。

将其更改为:

while(i < hello.length())

或者最好使用迭代器。

while(i < hello.length())
    {
        cout << setfill('0') << setw(2) << hex << (unsigned int)hello[i];
        i++;
    }

您的原始循环永远不会结束。对于计数索引,我发现for循环语法更适合。

您在 while 循环中缺少条件。

 while(i < hello.length())
    {
        cout << setfill('0') << setw(2) << hex << (unsigned int)hello[i];
        ++i;
    }

我更喜欢 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::dequestd::list,那么迭代器仍然可以工作。

在另一种风格说明上,我会避免 C 型铸造。那是你(unsigned int)的地方.请改用 static_cast<unsigned> (*it) 。这通过只给你实际追求的施法能力来传达你的意图。C 样式转换的范围要广泛得多,但此处想要的只是在整数类型的大小之间进行转换。