C++超出下标范围
C++ Out of Subscript Range
我正在运行一个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::deque
或std::list
,那么迭代器仍然可以工作。
在另一种风格说明上,我会避免 C 型铸造。那是你(unsigned int)
的地方.请改用 static_cast<unsigned> (*it)
。这通过只给你实际追求的施法能力来传达你的意图。C 样式转换的范围要广泛得多,但此处想要的只是在整数类型的大小之间进行转换。
相关文章:
- 尝试通过多个向量访问变量时,向量下标超出范围
- 矢量下标超出SFML游戏中的范围
- 运行时错误:矢量下标超出范围:正在检查空集
- 如果变量数据包含大于 vector 所有元素的整数,则仅在视觉工作室上接收"矢量下标超出范围"?
- 编译期间矢量下标超出范围
- C++ 调试断言失败 - 矢量下标超出视觉工作室的范围
- 对矢量来说是全新的.矢量下标超出范围
- C++十进制到十六进制(字符串下标超出范围)
- 创建结构体向量,表达式:向量下标超出范围
- 读取矢量时矢量下标超出范围
- 断言失败错误,C++中的矢量下标超出范围问题
- 如何在 Linux 上强制执行矢量下标超出范围的调试断言
- 表达式:矢量下标超出范围
- 矢量下标超出范围,带有嵌套的 for 循环
- 向量下标超出向量向量的范围
- gcc8.2如何启用警告:数组下标在数组范围之上[-warray-bounds]
- 向量下标出的范围错误.即使向量的索引大于访问数据的索引,也会发生误差
- std::vector<std::vector<int>>:调试断言失败。C++矢量下标超出范围保留内存
- 重命名两个目录中的文件名,如果它们之间的某些字符匹配 - 矢量下标超出范围
- 行进立方体重建 - 向量下标超出范围