Note that there are some explanatory texts on larger screens.

plurals
  1. POWriting file data into a class? C++
    text
    copied!<p>I have a class that looks like this:</p> <pre><code>class Test { public: Test() {} ~Test() {} //I kept these public for simplicity's sake at this point (stead of setters). int first_field; int second_field; int third_field; string name; }; </code></pre> <p>My .txt file looks like this:</p> <pre><code>1 2323 88 Test Name A1 2 23432 70 Test Name A2 3 123 67 Test Name B1 4 2332 100 Test Name B2 5 2141 98 Test Name C1 7 2133 12 Test Name C2 </code></pre> <p>I would like to be able to read in each line from the file into a vector, so my current code for that looks like this:</p> <pre><code>#include "Test.h" #include &lt;fstream&gt; #include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; using namespace std; int main() { ifstream file; vector&lt;Test&gt; test_vec; file.open("test.txt"); if(file.fail()) { cout &lt;&lt; "ERROR: Cannot open the file." &lt;&lt; endl; exit(0); } while(!file.eof()) { string input; if(file.peek() != '\n' &amp;&amp; !file.eof()) { Test test; file &gt;&gt; test.first_field &gt;&gt; test.second_field &gt;&gt; test.third_field; getline(file, input); test.name = input; test_vec.push_back(test); } } return 0; } </code></pre> <p>So, I'm stuck at the portion where I want to read in that data... I've tried input stream operator and it doesn't do anything; other options give me errors. I would also like to preserve the formatting if possible. What I want to do later is be able to sort that vector by different data fields in the class.</p> <p>Any ideas?</p> <p><strong>EDIT: Problem has been solved and the code has been edited to reflect it. Thank you for all the help. :)</strong></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