I have been working on an array that needs to return the number of even numbers from a file. My problem is that no matter what I have in the file for numbers it always says there are 5 numbers. I think the problem is in my for statements but I'm not sure how to use them without the way they currently are.
#define MAX_ROWS 3
#define MAX_COLUMNS 2
ifstream in;
void main()
{
int E;
in.open("numbers.txt"); //opens the input file
if (!in) //checks for the input file
{
cerr << "****Error numbers file does not exist****" << '\n';
exit(1);
}
in >> E;
int A[MAX_ROWS][MAX_COLUMNS] = { E }; //assign values to the array
int B, C, D=0;
for (B = 0; B < 3; B++)
{
for (C = 0; C < 2; C++)
{
if (A[B][C]%2 == 0) //Check for even values
{
D++;
}
}
}
cout << "There are " << D << " even numbers" << '\n'; //output total even values
cout << "The program is complete!"<<'\n';
}
The program woks fine when I have the values declared in the program, it just doesn't work right when I am reading from a file.
#define MAX_ROWS 3
#define MAX_COLUMNS 2
int A[MAX_ROWS][MAX_COLUMNS] = { { 3, 2 }, { 4, 5 }, { 2, 2 } }; //assign values to the array
int B, C, D;
int _tmain(int argc, _TCHAR* argv[])
{
for (B = 0; B < 3; B++)
{
for (C = 0; C < 2; C++)
{
if (A[B][C]%2 == 0) //Check for even values
{
D++;
}
}
}
cout << "There are " << D << " even numbers" << '\n'; //output total even values
cout << "The program is complete!"<<'\n';
return 0;
From looking over my code and other examples on the site, I feel like my values from the file aren't getting passed into the program. As a result it is simply giving me to size of the two arrays, am I right?
What I think happened:
One value only (1st in file) is read into E.
The array A[][] is initialized with A[0][0] = E and all other elements = 0.
If 1st value is 3 (like in top code example) then you have 1 odd #(3) and 5 even #'s(0).
Output is as expected.
Try this to replace all code in lines 16 through 30 of 1st code shown:
Values are read one by one from the file into E, once per iteration of the while loop.
Each value of E is checked to see if it's even and if so, D is incremented.
The while loop goes until there is no more integer data to read from the file.
in >> E evaluates as false when it reaches the end of the file so the while loop is terminated.
This method also allows there to be any number of integers in the file, not just 6 as in the array examples you had.
#include "stdafx.h"
#include <iostream>
#include <fstream>
usingnamespace std;
#define MAX_ROWS 3
#define MAX_COLUMNS 2
ifstream in;
void main()
{
int E;
in.open("numbers.txt"); //opens the input file
if (!in) //checks for the input file
{
cerr << "****Error numbers file does not exist****" << '\n';
exit(1);
}
int D = 0;
while (in >> E)
if (E % 2 == 0)D++;
cout << "There are " << D << " even numbers" << '\n'; //output total even values
cout << "The program is complete!"<<'\n';
in.close();
}