Finding min and max value in a struct

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • toodlez
    New Member
    • Nov 2008
    • 2

    #1

    Finding min and max value in a struct

    Hi, I'm pretty new to C++ and I want to find the min and max value in a collection of values. The pairs are in a text file and contain a descriptor and a value. For example: Bob 120 Jack 7 Larry -90 Pete 500 Ron -8 Here is the code I've worked out so far. I want to set min at first to be equal to the first value in the collection (120) but I have no clue how to do that. Any help would be appreciated.

    Code:
    #include <iostream>
    #include <fstream>
    using namespace std;
    
    struct collection
    {
    char descriptor[20];
    float value;
    };
    
    bool trytoread(ifstream *ps,collection *ppt)
    {
    *ps>>(*ppt).descriptor;
    if (!*ps)
        return false;
    *ps>>(*ppt).value;
    if (!*ps)
        return false;
    return true;
    }
    
    int main()
    {
    char fileName[80];
    cout<<"what input file? ";
    cin>>fileName;
    ifstream infile;
    infile.open(fileName);
    collection c;
    if (!infile)
        {
        cout<<"BAD OPEN";
        exit(1);
        }
    float min;
    while(trytoread(&infile,&c))
        {
            min=c.value;  //Want to set min to be the first value in the collection (120)
        if (min>c.value)
            min=c.value;
        }
    cout<<"the minimum value is: "<<min<<endl;
    return 0;
    }
    Last edited by toodlez; Nov 17 '08, 06:18 AM. Reason: typos
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    use a boolean variable (that many people tend to call something like firstTime). Set it to true outside the loop.

    Inside the loop if it is true then set min to c.value and firstTime to false othewise perform your min>c.value comparison.

    This is just a simple way to mark the first iteration of a loop. Note that for for loops it would be unnecessary as you can just use the loop variable plus the initial condition of that variable to detect the first iteration.

    Comment

    • toodlez
      New Member
      • Nov 2008
      • 2

      #3
      thank you for the help! that worked great.

      Comment

      Working...