加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C超出下标范围

发布时间:2020-12-16 10:21:47 所属栏目:百科 来源:网络整理
导读:我正在运行一个C程序,它应该将字符串转换为十六进制.它编译但在运行时我的错误说: Debug Assertion Failed! (Oh no!) Visual Studio2010includexstring Line 1440 Expression: string subscript out of range 我没有选择中止…似乎它将它转换为错误点,所
我正在运行一个C程序,它应该将字符串转换为十六进制.它编译但在运行时我的错误说:

Debug Assertion Failed! (Oh no!)

Visual Studio2010includexstring

Line 1440

Expression: string subscript out of range

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

#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;
}

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

解决方法

你的状况不正确:

while(hello.length())

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

将其更改为:

while(i < hello.length())

或者更好地使用迭代器.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读