Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>Update:</strong> Turns out that this method, while following STL idioms well, is actually surprisingly inefficient! Don't do this with large files. (See: <a href="http://insanecoding.blogspot.com/2011/11/how-to-read-in-file-in-c.html" rel="noreferrer">http://insanecoding.blogspot.com/2011/11/how-to-read-in-file-in-c.html</a>)</p> <p>You can make a streambuf iterator out of the file and initialize the string with it:</p> <pre><code>#include &lt;string&gt; #include &lt;fstream&gt; #include &lt;streambuf&gt; std::ifstream t("file.txt"); std::string str((std::istreambuf_iterator&lt;char&gt;(t)), std::istreambuf_iterator&lt;char&gt;()); </code></pre> <p>Not sure where you're getting the <code>t.open("file.txt", "r")</code> syntax from. As far as I know that's not a method that <code>std::ifstream</code> has. It looks like you've confused it with C's <code>fopen</code>.</p> <p><strong>Edit:</strong> Also note the extra parentheses around the first argument to the string constructor. <em>These are essential</em>. They prevent the problem known as the "<a href="http://web.archive.org/web/20110426155617/http://www.informit.com/guides/content.aspx?g=cplusplus&amp;seqNum=439" rel="noreferrer">most vexing parse</a>", which in this case won't actually give you a compile error like it usually does, but will give you interesting (read: wrong) results.</p> <p>Following KeithB's point in the comments, here's a way to do it that allocates all the memory up front (rather than relying on the string class's automatic reallocation):</p> <pre><code>#include &lt;string&gt; #include &lt;fstream&gt; #include &lt;streambuf&gt; std::ifstream t("file.txt"); std::string str; t.seekg(0, std::ios::end); str.reserve(t.tellg()); t.seekg(0, std::ios::beg); str.assign((std::istreambuf_iterator&lt;char&gt;(t)), std::istreambuf_iterator&lt;char&gt;()); </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. 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