Note that there are some explanatory texts on larger screens.

plurals
  1. POReplace in string iteration (out_of_range)
    text
    copied!<p>I wrote a function which percent-encodes a string, as follows:</p> <pre><code>string percent_encode(string str) { string reserved = // gen-delims ":/?#[]@" // sub-delims "!$&amp;'()*+,;=" ; for(string::iterator i = str.begin(); i &lt; str.end(); i++) { int c = *i; // replaces reserved, unreserved non-ascii and space characters. if(c &gt; 127 || c == 32 || reserved.find(*i) != string::npos) { std::stringstream ss; ss &lt;&lt; std::hex &lt;&lt; c; str.replace(i, i + 1, "%" + ss.str()); } } return str; } </code></pre> <p>When I call this function for a string like "a&amp;b", an out_of_range exception is thrown:</p> <pre><code>terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::replace </code></pre> <p>I traced this exception with a debugger and saw, that the replacing worked well, but it iterates somehow beyond end();</p> <p>This is what I get, when I watch the iterator "i":</p> <pre><code>{_M_current = 0x7fc43d61bd78 "a&amp;b"} {_M_current = 0x7fc43d61bd79 "&amp;b"} {_M_current = 0x7fc43d61bd7a "b"} {_M_current = 0x7fc43d61bd7b ""} {_M_current = 0x7fc43d61bd7c "o = a&amp;b\n"} {_M_current = 0x7fc43d61bd7d " = a&amp;b\n"} </code></pre> <p>Then it tries to replace "=" and fails with an out_of_range exception. I do not understand, how it is possible for the iterator to get obviously beyond end().</p> <p>I would be appreciated, if someone could explain me, how this is possible, because I could not find someone in the web, who had the same problem.</p> <p>Thanks and regards,</p> <p>reeaal</p> <p>Edit:</p> <p>Argh, I really thought to complicated. x) This is how I solved it now. </p> <pre><code>string percent_encode(string str) { string reserved = // gen-delims ":/?#[]@" // sub-delims "!$&amp;'()*+,;=" ; std::stringstream ss; for(string::iterator i = str.begin(); i &lt; str.end(); i++) { // encodes reserved, unreserved non-ascii and space characters. int c = *i; if(c &gt; 126 || c == 32 || reserved.find(*i) != string::npos) { ss &lt;&lt; '%' &lt;&lt; std::hex &lt;&lt; c; } else { ss &lt;&lt; *i; } } return ss.str(); } </code></pre> <p>Thanks Diego :)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload