235k views
3 votes
Write a program that reads a stream of integers from a file and prints to the screen the range of integers in the file (i.e. [lowest, highest]). You should first prompt the user to provide the file name. You should then read all the integers from the file, keeping track of the lowest and highest values seen in the entire file, and only print out the range of values after the entire file has been read.

User Romerun
by
6.0k points

1 Answer

4 votes

Answer:

This question is answered using C++ programming language

#include <fstream>

#include<iostream>

using namespace std;

int main() {

string fname;

cout<<"Enter Filename: ";

cin>>fname;

int lowest = 0;

int highest = 0;

ifstream ifs(fname);

int x;

while (ifs >> x){

if(x < lowest){

lowest= x;

}

if(x > highest) {

highest = x;

}

}

ifs.close();

for(int i = lowest; i<=highest;i++)

{

cout<<i<<" ";

}

}

Step-by-step explanation:

This line declares fname as string

string fname;

This prompts user for filename

cout<<"Enter Filename: ";

This gets filename

cin>>fname;

This declares and initializes lowest to 0

int lowest = 0;

This declares and initializes highest to 0

int highest = 0;

This defines the file using ifstream

ifstream ifs(fname+".txt");

This declares x as integer. x is used to read integers in the file

int x;

The following iteration will be repeated until there is no other integer to be read from the file

while (ifs >> x){

This checks for lowest

if(x < lowest){

lowest= x;

}

This checks for highest

if(x > highest) {

highest = x;

}

}

This closes the file. i.e. the file has been read

ifs.close();

The following iteration prints the range of values from lowest to highest

for(int i = lowest; i<=highest;i++) {

cout<<i<<" ";

}

Please note that the filename must be entered with its extension

User Yangshun Tay
by
6.3k points