Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Rather than find your bug, let's try to teach you some practical lessons. Here are my C++ rules for C programmers:</p> <p>1) Don't use pointers to track your data. The standard containers work just fine for that.</p> <p>2) Don't use pointers to manage your strings. The standard string type works just fine for that.</p> <p>3) Don't use pointers for anything else, until you need to learn how polymorphism works.</p> <p>4) Don't use malloc at all. Ever.</p> <p>5) Don't use new, hardly at all.</p> <p>The neat thing about not using pointers (or arrays), is that you will never make pointer bugs. No more buffer overflows, no more segmentation faults. Joy!</p> <p>Here is my translation of your program into idiomatic C++. Because I let <code>std::list</code> do all of the list management, all of the silly headPtr, nextPtr, etc, goes away. Because I let <code>std::string</code> do all of the string management, I don't need to <code>malloc(strlen())</code> (or fix my bug and <code>malloc(strlen()+1)</code>. Because I use the RAII idiom, I don't have to worry about closing my files.</p> <p>It all just works.</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;string&gt; #include &lt;list&gt; #include &lt;cstdlib&gt; #include &lt;sstream&gt; using std::string; using std::cout; using std::list; using std::ifstream; using std::stringstream; int main() { // Declare variables list&lt;string&gt; list; cout &lt;&lt; "Reading from data files, please be patient...\n"; // Loop through files for (int i = 1880; i &lt;= 2009; i++) { stringstream fileName; fileName &lt;&lt; "data/yob" &lt;&lt; i &lt;&lt; ".txt"; ifstream filePtr(fileName.str().c_str()); if(!filePtr.is_open()) { cout &lt;&lt; "Error opening input file: " &lt;&lt; fileName.str() &lt;&lt; " ...check location of data files\n"; exit(-1); // Exit program } string inputLine; while (filePtr &gt;&gt; inputLine) { list.push_back(inputLine); } } // End of for (i = 1880... cout &lt;&lt; "Done reading from data files...\n"; } // End of main function </code></pre>
 

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