title: C++ loading numbers from a file then finding the sum
body: <p>I posted something on this last night, but I have decided to change my approach slightly as I wasn't fully understanding the code I was trying to use.</p>
  
  <p>I apologise as I know this topic has been done to death but I'd like a little help with the code I've written.</p>
  
  <p>I'm loading a .txt file from my computer with 100 integers in. They are each on new lines. </p>
  
  <p>This is my code so far:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;fstream&gt;
  #include &lt;string&gt;
  #include &lt;cstdlib&gt;
  
  using namespace std;
  
  int main ()
  {
      ifstream fout;
      ifstream fin;
  
  
  
      string line;
      ifstream myfile ("100intergers.txt");
      if (myfile.is_open())
      {
          while ( getline(myfile,line) )
          {
              cout &lt;&lt; line &lt;&lt; '\n';
          }
  
          // Closes my file
          myfile.close();
  
  
          // If my file is still open, then show closing error
      if (myfile.is_open())
          cerr &lt;&lt; "Error closing file" &lt;&lt; endl;
          exit(1);
      }
  
  
      int y = 0;
      int z = 0;
      int sum = 0;
      double avg = 0.0;
  
      avg = sum/(y+z);
      cout &lt;&lt; endl &lt;&lt; endl;
      cout &lt;&lt; "sum = " &lt;&lt; sum &lt;&lt; endl;
      cout &lt;&lt; "average = " &lt;&lt; avg &lt;&lt; endl;
  
      // checking for error
      if (!myfile.eof())
      {
          cerr &lt;&lt; "Error reading file" &lt;&lt; endl;
          exit(2);
      }
  
      // close file stream "myfile"
      myfile.close();
  
      return(0);
  
  }
  </code></pre>
  
  <p>When I run it I get exit code 1 (as well as a list of my 100 integers).</p>
  
  <p>Which means my if clause isn't the right choice, what's a better alternative?</p>
  
  <p>If I delete that bit completely, it fails to run do to an arithmetic error which I think is 0/0*0</p>
  
  <p>Also I think the code I've written for the .txt file is for words, not numbers, but when I change string to int it really bugs and tells me I have more problems than without. </p>
  
  <p>Finally - after this I want to make an array to calc variance - any tips?</p>
  
  <p>Cheers </p>
  
  <p>Jack</p>