Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There's no standard and <em>fast</em> way to do this. I can think of some options.</p> <hr> <p>Suppose we have:</p> <pre><code>char *text = new char[20]; cin &gt;&gt; text; </code></pre> <p>Note - we <strong><em>need</em></strong> to know that the capacity is 20! I'd recommend you to use some constant for this, especially if this will be used for other strings, too.</p> <hr> <p>Okay, first option - use <code>std::stringstream</code></p> <pre><code>std::stringstream ss; ss &lt;&lt; setw( 20 - 1 ) &lt;&lt; setfill( '-' ) &lt;&lt; text; // ^^^^ we need one byte for the '\0' char at the end ss &gt;&gt; text; </code></pre> <p>But this is rather slow. </p> <hr> <p>Fill the chars by hand:</p> <pre><code>int length = strlen( text ); for( int i = length; i &lt; 20 - 1; ++i ) // again - "20-1" - '\0' { text[ i ] = '-'; } text[ 20 - 1 ] = '\0'; // don't forget to NULL-terminate the string </code></pre> <hr> <p>And <strong><em>the best way</em></strong>, according to me - get rid of these <code>char*</code> things (you have tagged the question as <a href="/questions/tagged/c%2b%2b" class="post-tag" title="show questions tagged 'c++'" rel="tag">c++</a> ) and just use <code>std::string</code>.</p> <pre><code>std::string sText; std::cin &gt;&gt; sText; sText.resize( 20, '-' ); // NOTE - no need to NULL-terminate anything </code></pre> <p><em><strong>Voilà!</em></strong> (:</p> <p>This way is much more clear and you don't need to carry about using <code>delete[] text;</code> at the end (which is not that trivial sometimes, especially in case of some exception before <code>delete[]</code> - this will give you 100% memory leak. Of course, you can always use smart pointers.. but smart pointers for this?! :) )</p> <hr> <p>Of course, you can write <code>19</code> instead of <code>20-1</code>, I just wanted to "highlight" the <code>-1</code>, in case that you use some constant. </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