Hi I need some help.
I am trying to write a program that will search a file for numbers of type int and write the largest and the smallest numbers to the screen. This is how far I got but when I it came to writing the code that would read the file and output the largest and smallest to the screen I kinda uh ...... yeah.

Could someone walk me through how I would do it?

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

int main()
{
	ifstream fin;
	ofstream fout;

	fin.open("getfromthisfile.txt");
	if(fin.fail())
	{
		cout << "Input file opening failed.\n";
		exit(1);
	}
	
	fout.open("sendtothisfile.txt");
	if(fin.fail())
	{
		cout << "Input file opening failed.\n";
		exit(1);
	}

how I think I should do it ... but most likely will not work...

int next;
	int largest=0;
	int smallest;

	while(! fin.eof())
	{
		next++;
		if(next>largest)
		{
			largest=next;
		}
		fin.get(next);
		fout << "The largest number in getfromthisfile.txt is " << largest <<  endl;
		if(next<smallest)
		{
			smallest=next;
		}
		fin.get(next);
		fout << "The smallest number in getfromthisfile.txt is " << smallest << endl;
	}
	fin.close();
	fout.close();
	system("pause");
	return 0;
}

yeah I am completely new to C++ ... ha :)

Dani AI

Generated

Good question, and nice progress so far. A couple of things are tripping you up, which already hinted at: do not use get() for integers and avoid while(!eof()). The eof() flag is only set after a read fails, so loops built around it commonly miss or double-process the last value. Also, initialize your min/max from the first successfully read integer rather than guessing defaults.

Here is the tight, idiomatic pattern that handles empty files and reads every int, regardless of line breaks or spaces:

#include <iostream>
#include <fstream>

int main() {
    std::ifstream in("getfromthisfile.txt");
    if (!in) { std::cerr << "Input file opening failed.\n"; return 1; }

    int x, mn, mx;
    if (!(in >> x)) { std::cerr << "No integers found.\n"; return 1; } // empty or non-numeric
    mn = mx = x;

    while (in >> x) {               // keep reading ints until extraction fails
        if (x < mn) mn = x;
        if (x > mx) mx = x;
    }

    std::cout << "largest: " << mx << "\nsmallest: " << mn << '\n';
}

Notes tied to the thread:

  • ’s question matters: this works because the file is ints only. If non-numeric tokens can appear, you must decide whether to stop on them or skip them.
  • , the reason a trailing line like 100 -55 did not update the smallest is the while(!eof()) pattern, not the newline. >> skips whitespace, so newlines are fine; switching to while (in >> x) fixes it.
  • Minor bug from earlier snippets: after opening the output file, check fout.fail(), not fin.fail(). And do not increment the data you read (e.g., next++); that changes the values you are trying to compare.

Recommended Answers

All 6 Replies

post the contents of the input file. Does it contain numeric digits only or can it contain non-numeric characters? How to parse the file will depend on what it contains.

post the contents of the input file. Does it contain numeric digits only or can it contain non-numeric characters? How to parse the file will depend on what it contains.

Oh yeah sorry about that :) it contains numeric digits only.

Hello

First, variables must be initialize before using them, e.g. smallest has been defined but never been initialized. So put these two lines just before your while loop:

fin >> next;
smallest = largest = next;

Second, do not use fin.get(next) for this reads one char only, and not an int, result would be DT mismatching. The >> operator is much more powerful for it is overloading with almost all data types of c++, e.g. istream& operator>> (int& val ), just that what you need here.

Third, your while loop starts fine. But inside there is some trouble.

Think of redesign it that way:

while (! fin.eof())  // if you make use of eof(), fin should has been read once at least
{
     // 1. process your just  read-in data here:
     if ( next < smallest ) ...; else; if ( largest < next ) ...;

     // 2. read next data from file 
     fin >> next;  // again, do not use fin.get(.) for data type mismatching
} 

// coming here, smallest and largest shoud contain their appropriate values.
// Sorry, I don't have tested this code, so there might be some minor mistakes.

I hope these hints may help you a little.

-- tesu

Awesome, I got it. Thank you :) for the help

:) :) :) :) :) :)
:) :) :) :) :) :)

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

int main()
{
	ifstream fin;
	ofstream fout;

	fin.open("getfromthisfile.txt");
	if(fin.fail())
	{
		cout << "Input file opening failed.\n";
		exit(1);
	}
	
	fout.open("sendtothisfile.txt");
	if(fin.fail())
	{
		cout << "Output file opening failed.\n";
		exit(1);
	}

	int next;
	int largest=0;
	int smallest;

	fin >> next;
	smallest = largest = next;
	while(! fin.eof())
	{
		
		if ( next < smallest ) 
			smallest=next;

		else if ( largest < next )
			largest=next;

		   fin >> next;
	}
	fout << "The largest number in getfromthisfile.txt is " << largest <<  endl;
	fout << "The smallest number in getfromthisfile.txt is " << smallest << endl;
	fin.close();
	fout.close();

	cin.ignore(numeric_limits<streamsize>::max(),'\n');
	return 0;
}

i kinda followed tesujis advice...and its technically working..given the numbers:

0 1 2 3 4 5 6 7 8 9 10
-1 0 1 2 3 4 5 6 7 8 9
-2 -1 0 1 2 3 4 5 6 7 8
-3 -2 -1 0 1 2 3 4 5 6 7
-4 -3 -2 -1 0 1 2 3 4 5 6
-5 -4 -3 -2 -1 0 1 2 3 4 5
-6 -5 -4 -3 -2 -1 0 1 2 3 4
-7 -6 -5 -4 -3 -2 -1 0 1 2 3
-8 -7 -6 -5 -4 -3 -2 -1 0 1 2
-9 -8 -7 -6 -5 -4 -3 -2 -1 0 1
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0

but when i add a new line lets say, 100 -55 below.. it only reads 100 as largest and not -55 as the smallest..what happened?

is the code wrong? im new to streamfiles....help?

try copying fin >> next; from the main function and pasting to the while loop, just before the if statement begins.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.