# input from file, output to screen



## sami0152 (Sep 17, 2010)

I need to write a program that takes its input from a file of numbers of type double and outputs the average of the numbers in the file to the screen. 
I keep getting 'error opening input file'. where am i supposed to save num.txt??


#include <iostream> 
#include <fstream> 

using namespace std; 

int main() 
{ 
int n; 
ifstream Input; 
ofstream Output; 

Input.open("num.txt"); 

if(Input.fail( )) 
{ 
cout << "error opening input file"<<endl; 
 return 1; 
} 

Output.open("average.txt"); 

if(Output.fail( )) 
{ 
cout << "error opening output file"<<endl; 
return 0; 
} 


int total=0; 
int count=0; 

while(!Input.eof()) 
{ 
Input>>n; 
total=total+n; 
count++; 
} 

float average=0; 

average=float(total)/float(count); 
cout<<"sum "<<total<<" count "<<count<<" average "<<average; 
Output<<average; 

Input.close(); 
Output.close(); 

return 0; 

}


----------



## TechMan100 (Sep 28, 2010)

Since you didn't give a path to the open method, put the _num.txt_ file in the same directory as the executable.

*Instead of this:*


```
if(Input.fail( ))
{   
 cout << "error opening input file"<<endl;  
 return 1; 
}
```
*

Try this type of construct:*


```
if (Input.is_open())
{
  while (Input.good())
  {
    /* add processing here */
  }
  Input.close();
}
else
{
  cout << "Error opening file";
}
```


----------

