Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by NavBot (jp)

...

return the character stored at the specified position if pos &lt; < size(). If pos == size(), the const
version returns the terminating null character type value. Otherwise, the behavior is undefined.

...

Code Block
bgColor#FFcccc
string bs(&amp;quot;01234567&amp;quot;"01234567");
size_t i = f();

bs[i] = '\0';

...

Wiki Markup
This compliant solution uses the {{basic_string at()}} method, which behaves in a similar fashion to the index {{operator\[\]}} but throws an {{out_of_range}} exception if {{pos &amp;gt;>= size()}}.

Code Block
bgColor#ccccff
string bs(&amp;quot;01234567&amp;quot;"01234567");
try {
  size_t i = f();
  bs.at(i) = '\0';
}
catch (...) {
  cerr &amp;lt;&amp;lt; &amp;quot;<< "Index out of range&amp;quot; &amp;lt;&amp;lt;" << endl;
}

In any case, the behavior of the index operators is unchecked (no exceptions are thrown).

...

Code Block
bgColor#FFcccc
string bs(&amp;quot;01234567&amp;quot;"01234567");
for (int i=0; i &amp;lt;< 100; i++) {
  bs[i] = '\0';
}

...

Code Block
bgColor#ccccff
size_t const max_fill = 100;
std::string bs(&amp;quot;01234567&amp;quot;"01234567");

fill(bs.begin(), bs.begin()+std::min(max_fill, bs.length()), '\0' );

...