Read a file and determine max and min int in file

I have some code that reads a file and finds the integer with the max value and the integer with the least value in a file and out puts those values to the screen, only if the file contains only integers. But how can I ammend this code to read files with other characters such as punctuation and alphabetic chars and still perform the same output.

Here is my code:

//Header files
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <climits>

using namespace std;

int main()

//Type int variables declared local to main

int largest = -INT_MAX ; int smallest = INT_MAX;
int number;

//Type ifstream variables declared local to main
ifstream indata;

//Type char variables local to main
char FileName[15];
char ans; //variable used as a condition for the do while loop, allowing the user to continue to input additional files

//Prompt user the purpose of the program
cout << " This program reads a file containing integers and outputs\n" " the LARGEST and the smallest integers to the screen."
<< endl << endl;

//Do while loop allows the user to input additional files and run the program again
//Prompt user for file name
cout << "Enter the file name: " << endl;
cin >> FileName;
cout << endl << endl << endl << endl;

//Open file "data.dat" and assosicate it with "ifstream indata";

//Test if file "data.dat" is associated with indata
if (
//If association fails
cout << "File " << FileName << "failed to open.\n" << endl;


//If association is successful
cout << "File " << FileName << " successfully opened.\n" << endl;

//While loop if not EOF
while (! indata.eof())

//Read integers from file connected to ifstream "indata" into variable "number"
indata >> number;

if (number > largest)
largest = number;
if (number < smallest)
smallest = number;

}//end of while loop

//Close file "data.dat"

//Output largest integer and smallest integer to the monitor
cout << "The LARGEST integer in the file is: " << largest << endl;
cout << "The smallest integer in the file is: " << smallest << endl << endl;

//prompt to continue or not to continue
cout << "Enter Y or y to continue, anything else quits." << endl;
cin >> ans;
cout << endl;

}//determines if do while loop continues
while (ans == 'Y' || ans == 'y');

return 0;

Last edited on
Topic archived. No new replies allowed.