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 ,julia Lobur
Chapter:
I/o Streams As An Introduction To Objects And Classes
Exercise:
Programming Projects
Question:1 | ISBN:9780321531346 | Edition: 7

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. If this is being done as a class assignment, obtain the file name from your instructor.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{ 

	string inputFile;
	ifstream inFile;	
	int num;
	int largeNum;
	int smallNum;
	cout << "Enter a input file name: ";
	cin >> inputFile;
	inFile.open(inputFile);
	if(inFile.fail())
	{
		cout << inputFile << " File is not found. Give correct file name." << endl;
		system("pause");
		exit(1);
	} 
 
	if(inFile >> num)
	{

		largeNum = num;
		smallNum = num;
while(inFile >> num)
		{

			if(num > largeNum)
				largeNum = num;

			if(num < smallNum)
				smallNum = num;
		} 
		cout << "The largest number: " << largeNum << endl;
		cout << "The smallest number: "<< smallNum << endl;
	}
	else
	cout << "The file contains no numbers that is the file is empty." << endl;	
	system("pause");
	return 0;
} 

Input file data(NumbersFile.txt):

1 2 3 4 5 6
10 20 30 40 50

Output of the program:

 

0 0

Discussions

Post the discussion to improve the above solution.