This is my first time taking a C++ course and I can't seem to figure out how to count the number of even numbers in my text file. Any help would be greatly appreciated.
This is my assignment:
A) The number of numbers in the file:
B) The number of even numbers in the file:
C) The number of odd numbers in the file:
D) The sum of all the numbers in the file:
E) The average of all the numbers in the file:
What you referred to is part A and I got that down, but I'm trying to figure out part B.
if (filename.c_str()) {
while (inputFile >> number) {
counter++;
if (number % 2)
counter_even++; }
With this code, I get 101 as my output, but I don't know how to verify if I'm correct without having to actually count all the numbers myself.
#include <iostream>
#include <string>
#include <fstream>
usingnamespace std;
int main() {
ifstream inputFile;
string filename;
int number;
int average;
unsignedint sum = 0;
int counter = 0;
int counter_even = 0;
int counter_odd = 0;
cout << "Enter the file name: " << endl;
cin >> filename;
inputFile.open(filename.c_str());
if (filename.c_str()) {
while (inputFile >> number) {
counter++;
if (number % 2 == 0)
counter_even++;
else
counter_odd++;
sum += number;
average = sum / (counter_even + counter_odd);
}
}
cout << "The number of numbers in the file is " << counter << "." << endl;
cout << "The number of even numbers in the file is " << counter_even << "." << endl;
cout << "The number of odd numbers in the file is " << counter_odd << "." << endl;
cout << "The sum of the numbers in the file is " << sum << "." << endl;
cout << "The average of the numbers in the file is " << average << "." << endl;
return 0; }
Okay, so this is what I have so far. Now I just need input on whether or not this would give me an accurate display.