By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,431 Members | 1,739 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,431 IT Pros & Developers. It's quick & easy.

Finding min and max value in a struct

P: 2
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.

Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <fstream>
  3. using namespace std;
  4.  
  5. struct collection
  6. {
  7. char descriptor[20];
  8. float value;
  9. };
  10.  
  11. bool trytoread(ifstream *ps,collection *ppt)
  12. {
  13. *ps>>(*ppt).descriptor;
  14. if (!*ps)
  15.     return false;
  16. *ps>>(*ppt).value;
  17. if (!*ps)
  18.     return false;
  19. return true;
  20. }
  21.  
  22. int main()
  23. {
  24. char fileName[80];
  25. cout<<"what input file? ";
  26. cin>>fileName;
  27. ifstream infile;
  28. infile.open(fileName);
  29. collection c;
  30. if (!infile)
  31.     {
  32.     cout<<"BAD OPEN";
  33.     exit(1);
  34.     }
  35. float min;
  36. while(trytoread(&infile,&c))
  37.     {
  38.         min=c.value;  //Want to set min to be the first value in the collection (120)
  39.     if (min>c.value)
  40.         min=c.value;
  41.     }
  42. cout<<"the minimum value is: "<<min<<endl;
  43. return 0;
  44. }
  45.  
Nov 17 '08 #1
Share this Question
Share on Google+
2 Replies


Banfa
Expert Mod 5K+
P: 8,916
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.
Nov 17 '08 #2

P: 2
thank you for the help! that worked great.
Nov 18 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.