// This program takes a series of intergers and
// loads to a file, then reads from file and
// displays the least and greatest.
// Class: CIS2541-NET01
// Programmer: Mika Smith
#include <iostream>
#include <fstream>
usingnamespace std;
int main() {
int input; // Variable for number
int counter = 0; // Flag for loop
ofstream outputFile; // Initiate output
outputFile.open("integers.txt"); // Open file
while (counter != -99) { // loop to iterate inout
cout << "Enter a number: ";
cin >> input;
counter = input; // Set flag to input
if (input == -99){ // if statment to skip -99 in file output
continue; // Skips -99
}
else {
outputFile << input << endl; // Output data to file
}
}
cout << "Data saved to file\n";
outputFile.close(); // Close output file
ifstream inputFile; // Initiate input file
inputFile.open("integers.txt"); // Open file
cout << "reading data from file\n";
int least = 0; // Variable to least number
int greatest = 0; // Variabble for greatest number
int number; // Variable for loop
while (inputFile >> number) { // Loop to run through data
if (greatest < number) { // If statement to determine greatest or least number
greatest = number; // Set number to greatest
}
else {
least = number; // Set number to least
}
}
cout << "The greatest number is " << greatest << endl;
cout << "The least number is " << least << endl;
inputFile.close(); // Close input file
return 0;
}
The input is any integers the user enters. If I enter 1,2,3,4. I expect 4 to be greatest and 1 least. The program get greatest right but least is alway 0.
Also since you initialized minimum to zero only a negative value should change that value. One way of "fixing" this issue is to initialize the minimum and maximum to the first value.
Also breaking your program into several small functions would make testing much easier.