#include <iostream>
#include <fstream>
#include <iomanip>
usingnamespace std;
int main()
{
long number, average, testagainsthi, testagainstlow, total = 0;
char choice;
int menucount = 0, numcount = 0;
do
{
cout << "Make a selection from the list\n"
<< "1. Get the largest value\n"
<< "2. Get the smallest value\n"
<< "3. Get the sum of the values\n"
<< "4. Get the average\n"
<< "5. Get the number of values entered\n"
<< "6. End this program\n\n"
<< "Enter your choice --> ";
cin >> choice;
cout << endl;
if (choice >= '1' && choice <= '5')
{
menucount++; // menucount shows how many times the user has selected 1-5.
if (menucount == 1) // That is, if this is the first time the user has selected 1-5...
{
ifstream inputFile("TopicDin.txt"); // process the list. No need to process it more than once.
if (inputFile)
{
while (inputFile >> number)
{
inputFile >> number;
numcount++; // Find the number of values
if (numcount == 1)
testagainsthi = testagainstlow = number; // Assign the first number in the list to testagainsthi and testagainst low
if (number > testagainsthi) // Find the largest number
testagainsthi = number;
if (number < testagainstlow) // Find the smallest number
testagainstlow = number;
total += number; // Find the sum
}
average = (total / numcount); // Find the average
}
else
cout << "\nError opening file.";
}
if (choice == '1')
cout << fixed << setprecision(0) << "The largest value is " << testagainsthi << ".\n\n";
if (choice == '2')
cout << fixed << setprecision(0) << "The smallest value is " << testagainstlow << ".\n\n";
if (choice == '3')
cout << fixed << setprecision(0) << "The sum of the values entered is " << total << ".\n\n";
if (choice == '4')
cout << fixed << setprecision(0) << "The average of the values entered is " << average << ".\n\n";
if (choice == '5')
cout << fixed << setprecision(0) << "The number of values entered is " << numcount << ".\n\n";
}
elseif (choice == '6')
cout << "\nProgram ending\n\n";
else cout << endl << choice << " is an invalid value.\n\n";
} while (choice != '6'); // Matches the "do" at top of program. Don't redisplay menu if user enters 6.
return 0;
}
The loop starting on line 33 is supposed to examine all the contents of the file that was opened in line 30. The file is just a long list of random numbers, 1572 of them, in fact. However, my program is showing that there are only 786 numbers in the list, exactly half of the actual value. My program successfully found the largest value in the list because it's located in the first half of the list, but my program failed to find the smallest value in the list because it's located in in the second half of the list. My program's values for the sum and the average are obviously skewed as well because it only seems to be looking at half the list. Any idea why?
On line 33, you're reading the next int in the file into number, but then you're doing it again on line 35. Just delete line 35 and your program should work perfectly.