Input File won't open

First time asking for help so I am sorry if I do not give enough information.

For homework I need to take a file of numbers (double) and fine their average. But, I seem to be having an issue just opening the file.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;

void get_average(ifstream& input_file);
//  Precondition: Reads all the numbers from input file stream
//  Postcondition: Prints out to the screen the average of the numbers

int main()
{
    ifstream input_file;
    cout << "Opening program to find the average of the numbers on the input file." << endl;
    input_file.open("input.dat");
        if (input_file.fail()) {
            cout << "Opening input file failed." << endl 
                 << "Closing program now." << endl;
            exit(1);
        }
    
    get_average(input_file);
    
    input_file.close();
    
    cout << "End of Program";
    
    return 0;
}

void get_average(ifstream& input_file)
{
    double sum=0;
    double next;
    int count=0;
    input_file >> next;
    while (input_file >> next) {
        sum = sum + next;
        count++;
        input_file >> next;
    }
    cout << (sum/count);   
}
So this error message appears?

1
2
3
  if (input_file.fail()) {
            cout << "Opening input file failed." << endl 
                 << "Closing program now." << endl;


If so this just means your .exe can't find the text file specified. Either try moving it to the same folder as the .exe or the project directory for whatever IDE you are using.
I am using xCode. The file is in the folder. Here is a screen shot
https://www.dropbox.com/s/6df83h6c5db7usl/SS-error.png

UPDATE: Installed Neatbeans and for the most part the program started to work. Now the function get_average is only grabbing every other number in my file... This should be fun.
Last edited on
Try to give the absolute path to the file.
Topic archived. No new replies allowed.