Array not allowing data entry using ifstream.

Hello, I was writing this code where it basically reads integer values from a text file in one function, and then takes another function to sort out how many even numbers there are. Only problem is, it's not taking in any values. I even checked: I put all 3s in my txt file, and it's still saying that all ten values are even. Any suggestions on how to fix this?
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
43
  #include <iostream>
#include <fstream>
using namespace std;

void readfile(int Array[10]);
int check();

int main()
{
	check();
}

void readfile(int Array[10])
{
	ifstream Main;
	Main.open("Data.txt");

	for (int i = 0; i < 10; i++)
	{
		Main >> Array[i];
	}

}

int check()
{
	int Array[10], counter = 0;
	readfile(Array);

	for (int i = 0; i < 10; i++)
	{
		if (Array[i] % 2 == 0)
		{
			counter++;
		}
	}

	cout << "Total Even Numbers: " << counter << endl;

	return 0;
}

You aren't checking that the file has been opened successfully! Possibly:

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
#include <iostream>
#include <fstream>
using namespace std;

constexpr size_t MaxNos {10};

size_t readfile(int Array[MaxNos]);
size_t check();

int main() {
	cout << "Total Even Numbers: " << check() << '\n';
}

size_t readfile(int Array[MaxNos]) {
	size_t cnt {};
	ifstream Main("Data.txt");

	if (Main)
		for (; cnt < MaxNos && (Main >> Array[cnt]); ++cnt);

	return cnt;
}

size_t check() {
	int Array[MaxNos] {};
	size_t counter {};
	const size_t noNums {readfile(Array)};

	for (size_t i {}; i < noNums; counter += Array[i++] % 2 == 0);

	return counter;
}



Perhaps the file did not open or a read did fail. Those can be tested:
1
2
3
4
5
6
7
8
9
10
11
12
int readfile(int Array[], int N)
{
	ifstream Main;
	Main.open("Data.txt");
	if ( ! Main ) return 0; // file did not open
	int i = 0;
	while ( i < N && Main >> Array[i])
	{
		++i;
	}
	return i;
}


You can also print the values that you did read to see what you did read:
1
2
3
4
5
6
7
int Array[10], counter = 0;
int numbers = readfile(Array, 10);

for (int i = 0; i < numbers; i++)
{
	cout << i << ":  " << Array[i] << '\n';
}

You will remove the print loop, when that part works correctly.
Last edited on
Topic archived. No new replies allowed.