Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I think what's happening is that ofstream does not know how to serialize your struct.</p> <p>You may need to define >> and &lt;&lt; operators for InventoryItem:</p> <pre><code>ofstream&amp; operator &lt;&lt; ( ofstream&amp; ofs, InventoryItem&amp; ); ifstream&amp; operator &gt;&gt; ( ifstream&amp; ifs, InventoryItem&amp; ); </code></pre> <p>Edit::</p> <p>Here's a fully worked example. I was little off on the ifstream before the edit. <code></p> <pre><code>#include &lt; iostream &gt; #include &lt; fstream &gt; #include &lt; string &gt; struct InventoryItem{ std::string name; int id; float price; }; using std::ofstream; using std::ifstream; ofstream&amp; operator &lt;&lt; (ofstream&amp; ofs, InventoryItem&amp; ii) { ofs &lt;&lt; ii.name &lt;&lt; std::endl &lt;&lt; ii.id &lt;&lt; std::endl &lt;&lt; ii.price &lt;&lt; std::endl; return ofs; } ifstream&amp; operator &gt;&gt; ( ifstream&amp; ifs, InventoryItem&amp; ii ) { ifs &gt;&gt; ii.name &gt;&gt; ii.id &gt;&gt; ii.price; return ifs; } void printItem(const InventoryItem&amp; ii) { std::cout &lt;&lt; "Name: " &lt;&lt; ii.name &lt;&lt; std::endl &lt;&lt; "ID: " &lt;&lt; ii.id &lt;&lt; std::endl &lt;&lt; "Price: " &lt;&lt; ii.price &lt;&lt; std::endl; } int main() { ofstream outfile("testout.txt"); InventoryItem list[] = { {"Item1", 1, 1.5}, {"Item2", 2, 2.5} }; outfile &lt;&lt; list[0] &lt;&lt; list[1]; outfile.close(); std::ifstream infile("testout.txt"); InventoryItem list2[2]; infile &gt;&gt; list[0] &gt;&gt; list[1]; printItem(list[0]); printItem(list[1]); return 0; } </code></pre> <p></code></p> <p>The expected output is:</p> <pre> Name: Item1 ID: 1 Price: 1.5 Name: Item2 ID: 2 Price: 2.5 </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.
 

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