0

I writing a small program to determine the largest and smallest numbers read from a file. It works fine with all positive integers. However, when it comes to negative integers, things seem broken.

int get_largest(std::ifstream& fin)
{
    int largest, container;
    fin>>container;

    largest = container;

    while (fin>>container)
    {
        if (container>largest)
        {
        //bool check = (container>largest);
        largest = container;
        }
    }

return largest;
}

Here is the main function

#include <iostream>
#include <fstream>

int get_largest(std::ifstream& fin);

int main( int argc, const char * argv[])
{
using namespace std;
ifstream fin("numbers.dat");

 int smallest_value = get_smallest(fin);
 int largest_value = get_largest(fin);

cout<<"The smallest value is "<<smallest_value<<endl;
cout<<"The largest value is "<<largest_value<<endl;


return 0;
}

I pass in a list of numbers in a ifstream like this

 1
 2
 4
 10
 -2

The output says the largest number is -2 instead of 10. I tried using signed integers but it does not help.

Thank you for your time!

hacaoideas
  • 105
  • 8

0 Answers0