2012-04-17 167 views
3

我正在运行一个C++程序,该程序应该将字符串转换为十六进制。它汇编了运行时出错的错误信息:C++超出下标范围

Debug Assertion Failed! (哦不!)

视觉Studio2010 \包括\ 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; 
} 

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

回答

4

你而条件是不正确的:

while(hello.length()) 

循环永远不会终止和i变大(超过字符串长度减一),当你索引访问字符串你运行时断言。

将其更改为:

while(i < hello.length()) 

或者更好地利用迭代器。

+0

哦哇,为什么会编译然后给出这样一个奇怪的错误信息? (谢谢btw) – 2012-04-17 06:17:19

+0

@Howdy_McGee因为编译器不应该查找运行时错误。请注意,如果你在'while'表达式中有一个常量或局部变量 - 你会得到一个警告。但是函数调用会使编译器假定数据可能会改变。 – littleadv 2012-04-17 06:23:35

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

您原来的循环永远不会结束。为了统计索引,我发现for循环语法更适合。

+1

虽然你先回答,但你没有得到任何赞扬! +1 – 2012-04-17 06:18:20

+0

@Jesse谢谢:)有时我觉得我在拍摄更快的竞争对手...... – littleadv 2012-04-17 06:22:10

6

您不会从字符串中删除任何内容,因此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; 
} 
0

你错过了while循环的条件。

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

我宁愿迭代器在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风格的演员阵容更广泛,但你所需要的只是在整数类型的大小之间进行转换。