I/O file

Oct 13, 2015 at 3:07am
I have an issue with the code below. The least number is not reading right. any ideas why.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
  // 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>

using namespace 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;
		
}
Oct 13, 2015 at 3:17am
What input did you use when you created the file?

What output is your program producing, and what do you think the output should be?

Oct 13, 2015 at 3:24am
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.
Oct 13, 2015 at 3:29am
your logic is flawed.

if number is not greater than "greatest"
your setting least = number even if it's not less.
Oct 13, 2015 at 3:44am
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.

Topic archived. No new replies allowed.