SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,kenrick Mock
Chapter:
Streams And File Io
Exercise:
Programming Projects
Question:1 | ISBN:9780132846813 | Edition: 5

Question

Write a program that will search a file of numbers of type int and write the largest and the smallest numbers to the screen. The file contains nothing but numbers of type int separated by blanks or line breaks.


TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Complete Program:

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

int main()
{
	string fileName = "";
	int number;
	int largestNumber = INT_MIN;
	int smallestNumber = INT_MAX;	

	cout << "Enter the file name: ";
	cin >> fileName;

	ifstream infile;
	infile.open(fileName);

	if (infile.fail())
	{
		cout << fileName << " file cannot be opened!" << endl;
		exit(1);
	}

	while (infile >> number)
	{
		if (number > largestNumber)
			largestNumber = number;

		if (number < smallestNumber)
			smallestNumber = number;
	}

	cout << "The largest number in the file:  " << largestNumber << endl;
	cout << "The smallest number in the file: " << smallestNumber << endl;	

	return 0;
}

Input file: indata.txt

Output on console:

0 0

Discussions

Post the discussion to improve the above solution.