Read Integer Data From a File

I'm taking a beginner level C++ class, and have gotten stuck on one of the practice problems.

The assignment is to read in a file with a random set of integers and to print out the sum of the integers, the average, the number of even integers and the number of odd integers.

I have gotten as far as reading in the file, and I know I need to do some form of for loop or while loop to use the integers that are read in to compute the rest, but I'm not sure how to do that without knowing the exact number of integers or the range of the integers that will be in the files (We have 8 test files that range from 3 integers to 50 integers).

If someone could lead me in the right direction on how to write a loop to compute the sum of the integers without knowing how many intergers I will have, I believe I can figure out the rest.

This is the code I have so far that will read in the integers in the file and print them in the terminal.

#include <iostream>
#include <cmath>
#include <string>
#include <fstream>
#include <cstdlib>

using namespace std;

int main ()
{
int sum = 0.0; // sum of integers
double average = 0.0; // average of integers
int even = 0.0; // number of even integers
int odd =0.0; // number of odd integers

ifstream fin;
string file_name;
int x;

cout << "Enter the file name: ";
cin >> file_name;

fin.open(file_name.c_str(), ios::in);

if (!fin.is_open())
{

cerr << "Unable to open the file." << file_name << endl;
exit(10);

}

fin >> x;
while (!fin.fail())
{

cout << "Integer: " << x << endl;
fin >> x;

}

if (!fin.eof())
{

cerr << "Error reading file" << file_name << endl;
exit (20);

}

fin.close ();

return 0;

}
Here are 2 different ways of writing and storing integer values to and from 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

#include <fstream>
#include <iostream>

void write_txt_value(int v)
{
  std::ofstream txt_out("txt.out");
  txt_out << v;
}

int read_txt_value()
{
  std::ifstream txt_in("txt.out");
  int value;
  txt_in >> value;
  return value;
}

void write_bin_value(int v)
{
  std::fstream bin_out("bin.out",std::ios_base::binary|std::ios_base::out);
  bin_out.write((char*)&v,sizeof(int));
}

int read_bin_value()
{
  std::fstream bin_in("bin.out",std::ios_base::binary|std::ios_base::in);
  int value;
  bin_in.read((char*)&value,sizeof(int));
  return value;
}

int main()
{
  int value = -12345;
  write_txt_value(value);
  write_bin_value(value);
  std::cout << "Reading txt file value as integer: " << read_txt_value() << std::endl;
  std::cout << "Reading binary file value as integer: " << read_bin_value() << std::endl;
  return 0;
}
Topic archived. No new replies allowed.