0 Replies - 5457 Views - Last Post: 10 October 2012 - 10:14 PM Rate Topic: -----

#1 lexi0124  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 10-October 12

man/min program

Posted 10 October 2012 - 10:14 PM

hi, i need help with my homework, i have to create a program that reads integers from a txtpad and then check for the max and min, this is what i have so far...

// maxMin.cpp          

// Program reads integer values from a text file named "maxMin01.txt"
//  and writes out the largest and smallest values found.  Numbers in the
// file may be separated by blanks or line breaks.
// Run the program a 2nd time reading from "maxMin02.txt".
// Run the program a 3rd time reading from "maxMin03.txt".

#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;

int main() {
    // Declare input stream
    ifstream fin;
    int min, max, val;
    bool isFirst = true;
	
	// Open the file
    fin.open("//maxMin03.txt");
	
	// Check for successful file open
	if(fin.fail())
	{
		cerr << "Could not open the input file \\maxMin02.txt" << endl;
		exit(1);
	}
	
	
	// Loop to read numbers from the file into val and check for max and min
	// Use isFirst to know whether this is the first value read or not
	
	while(fin >> val)
	{
		if(val > isFirst && val > max)
		{
			max = val;
			isFirst = false;
		}
		else if(val < max && val < min )
		{
			min = val;
			isFirst = true;
		}
		
	}
	
	
	
	// Close the file
    fin.close();
	
	// Print the largest and smallest values
    cout << "Largest value is " << max << ", smallest value is " << min << "\n";
	
	return 0;  // successful completion
}




i really dont understand what to do with the isFirst, but this works perfect for the first file, but for the other two dont since on one i have all neg numbers and prints out that my largest number is zero, and on the other one i have non negative numbers and prints out that my smallest number is zero, and i think that reason is the boolean function since true is -1 to 1 and false is zero... but i dont know what to do....

the values for maxMin01.txt is:

Quote

-100 100
5 11 -101


maxMin02.txt:

Quote

300 200
578 2000 1010


manMin03.txt :

Quote

-400 -678
-300 -3000 -1100


thanks for your help!

Is This A Good Question/Topic? 0
  • +

Page 1 of 1