In: Computer Science
(C++) Create a data file and name it "input.txt". manually save 10 integers into the file. Write a program to read the data and calculate the average of events and odds, separately. Print out the average values.
#include <iostream>
#include <string>
#include <ctime>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
using namespace std;
int main()
{
// WRITING TO FILE
srand((unsigned)time(NULL));
//Declaring variables
string fileName = "input.txt";
float grade;
//Opening file
ofstream myfile;
myfile.open(fileName.c_str());
for (int i = 0; i < 10; i++) {
myfile<<(1 + rand() % 10)<<endl;
}
//Cloing file
myfile.close();
// READING FROM FILE
ifstream file;
file.open (fileName.c_str());
if (!file.is_open()) return 0;
int evenSum = 0, oddSum = 0, evenCount = 0, oddCount = 0;
int val;
while (file>>val)
{
if(val%2==0){
evenCount++;
evenSum+=val;
}
else{
oddCount++;
oddSum+=val;
}
}
cout<<"Average of evens = "<<(1.0*evenSum/evenCount)<<endl;
cout<<"Average of odds = "<<(1.0*oddSum/oddCount)<<endl;
return 0;
}