Spencer Cumbie Spencer Cumbie - 3 years ago 154
C++ Question

Writing and then displaying the number of even numbers written to a file (Beginner C++ Visual Studio)

In this program I need to write 3 integers to a text file and then display the number of even integers entered into the file. My code runs with no errors, the numbers get written to the file, but the cout statements within my if statements do not display for some reason.

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int num1 = 0;
int num2 = 0;
int num3 = 0;
ofstream outFile;
cout << "Enter three integers:\n";
cout << "#1: ";
cin >> num1;
cout << "#2: ";
cin >> num2;
cout << "#3: ";
cin >> num3;
outFile << num1 << endl << num2 << endl << num3 << endl;
outFile.close();
if (num1 % 2 == 0)
{
cout << "One even number was written to the file.";
}
else if (num2 % 2 == 0)
{
cout << "Two even numbers were written to the file.";
}
else if (num3 % 2 == 0)
{
cout << "Three even numbers were written to the file.";
}
else
{
cout << "No even numbers were written to the file.";
}
outFile.open("Text.txt", ios::app);
if (!outFile)
{
cout << "File did not open.";
return 1;
}
outFile << num1 << endl << num2 << endl << num3 << endl;
outFile.close();
return 0;
system("pause");


}

Answer Source

You could use different logic:

int count = 0;
if (num1 % 2 == 0)
{
  ++count;
}
if (num2 % 2 == 0)
{
  ++count;
}
if (num3 % 2 == 0)
{
  ++count;
}
std::cout << "There were " << count << " even numbers written to the file.\n";

The above code counts the number of even numbers, then outputs the value. No need for else clauses.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download