Versions Compared

Key

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

...

Code Block
bgColor#FFcccc
string bs("01234567""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 >>= size()}}.

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

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

...

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

...

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

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

...

Wiki Markup
\[[Seacord 05|AA. C++ References#Seacord 05]\] Chapter 2 Strings
\[[ISO/IEC 14882-2003|AA. C++ References#ISO/IEC 14882-2003]\] Section 21.3.4 basic_string element access

...

BSC33-C. Use valid references, pointers, and iterators to reference string objects      07. Characters and Strings (STR)      08. Memory Management (MEM)