Im not sure what im missing, or if i have something out of order. Were supposed to write a program that asks the user to enter a file name of a Random text file that we were provided that is just numbers.And validate that the file was opened. Once the user opens the file (Random.txt) successfully, the program should calculate the following:
A) The number of numbers in the file:
B) The even numbers in the file:
C) The 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:
#include <cstdlib>
#include <cmath>
#include <iomanip>
#include <fstream>
#include<iostream>
#include<string>
usingnamespace std;
int main()
{
// Declare Variables
int num_value;
int num_numbers;
int even;
int odd;
double sum;
double average;
string randfilename;
// Ask user for filename
cout << "Enter the filename : \n";
getline(cin,randfilename);
// Open file to read the data
ifstream inputFile(randfilename);
// Check to verify file opened correctly
if (inputFile.is_open())
{
cout<<"File opened successfully\n";
// If File successfuly opened then the data is read and specified operations are run
while (inputFile >> num_value)
{
cout << num_value << endl;
num_numbers++;
sum += num_value;
if(num_value%2==0)
even++;
else
odd++;
}
}
else
{
//Display an error message
cout << "Error opening the file\n";
}
if (num_numbers > 0)
average = sum / num_numbers;
else
average = 0.0;
cout << "Number of numbers: " << num_numbers << "\n";
cout << "The even numbers are: " << even << "\n";
cout << "The odd numbers are: " << odd << "\n";
cout << "Sum is: " << sum << "\n";
cout << "Average is: " << average;
inputFile.close();
return 0;
}
You need to initialize your variables before you use them. Afterwards it works.
Input file:
1 2 3 4 5
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13
Enter the filename :
numbers.txt
File opened successfully
1
2
3
4
5
Number of numbers: 5
The even numbers are: 2
The odd numbers are: 3
Sum is: 15
Average is: 3
Below is what i get as a result when I try to run the program. I initialized my variables, but still get this output....I have a random.txt file on my desktop that I can open fine on its own. But it appears the program is not opening the file...
Enter the filename :
random.txt
Error opening the file
Number of numbers: 0
The even numbers are: 0
The odd numbers are: 0
Sum is: 0
Average is: 0