C ++ from a substring range

I am running a C ++ program that should convert a string to hexadecimals. It compiles, but errors from me at runtime say:

Debugging Failed! (Oh no!)

Visual Studio2010 \ include \ xstring

Line 1440

Expression: string index out of range

And I have no choice to interrupt ... It seems he will convert it, although before the error, so I'm not sure what is happening. My code is simple:

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

What this program should do is convert each letter to hexadecimal - char to char.

+3
source share
5 answers

Invalid while condition:

while(hello.length())

, i (, ), , runtime.

:

while(i < hello.length())

.

+4

, 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;
}
+6
while(i < hello.length())
    {
        cout << setfill('0') << setw(2) << hex << (unsigned int)hello[i];
        i++;
    }

. , for .

+2

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
}

, ++ 11:

for (char const c : hello) {
    // String processing
}

, , , ++. , STL. , - std::deque std::list, .

C. (unsigned int). static_cast<unsigned> (*it). , , . C- , , , .

0

All Articles