Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Strings are like arrays, but the default constructor for a string creates an empty string. Why should it allocate more memory than it needs? Even if it does, there's no saying how much, or if it will be big enough for a filtered copy of fstring. I'm impressed it doesn't crash.</p> <p>A simple modification would be to change:</p> <pre><code>std::string newstring; </code></pre> <p>to:</p> <pre><code> std::string newstring(fstring.length(), '\0') </code></pre> <p>And after the loop add:</p> <pre><code> newstring.resize(x); </code></pre> <p>This will ensure that <code>newstring</code> will have at least enough room (probably more) during the filtration and will be trimmed down to the appropriate size when you are finished filtering. You may also be interested in the <a href="http://www.sgi.com/tech/stl/remove_copy_if.html" rel="nofollow noreferrer"><code>std::remove_copy_if</code></a> function in <code>&lt;algorithm&gt;</code>.</p> <p>E.g.</p> <pre><code>struct isnotdigit { bool operator()(char c) { return !isdigit(c); } }; std::string newstring(fstring.length(), '\0'); std::string::iterator i = std::remove_copy_if(fstring.begin(), fstring.end(), newstring.begin(), isnotdigit()); newstring.erase(i, newstring.end()); </code></pre> <p>As for converting a string to an integer / float, in addition to <code>atoi</code>, <code>strtol</code>, <code>atof</code>, <code>strtof</code>, etc. functions already mentioned you can also make using of the iostream library:</p> <pre><code> #include &lt;sstream&gt; std::string integer("23"); std::istringstream iss(integer); int result; iss &gt;&gt; result; std::string floatingpoint("3.14"); std::istringstream iss2(floatingpoint); double result2; iss2 &gt;&gt; result2; </code></pre> <p>Also, if you are familiar with the printf family of functions you may be interested in <code>scanf</code>, <code>sscanf</code></p> <pre><code> const char *s = "23"; int result; sscanf(s, "%d", &amp;result); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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