Hi
I have a particular problem in returning an element of a struct which matches a maximum of another element

here is part of the code, which will work, but does not display the details.title, which part of my original Struct declaration.

What am I doing wrong ?

int max = 0;
  
   for(int i = 0; i<PROCESSORS; i++)
     {
           
          if(details[i].TotalPoint > max)
             {
                max = details[i].TotalPoint;
             } 
           
     }

     cout<<"\n\n";
     cout<<"The Processor selected with " <<max<<" points\n"<< " is "<< details[i].title<< endl; 
  
  system ("PAUSE");
  return 0;

Recommended Answers

All 4 Replies

Line 14 : What do you think the value of i is? If I where the compiler I would not know!

Two problems. First, I suspect you're using Visual Studio 6.0, in which case you should be aware that standard C++ says i is out of scope when you use it outside of the loop. To be correct, you should change your loop from this:

for(int i = 0; i<PROCESSORS; i++)

To this:

int i;

for(i = 0; i<PROCESSORS; i++)

Second, after the loop runs, i == PROCESSORS. That's likely going to be out of bounds for your array, so when you set max, you should store the current index in another variable and use that to print the title later.

Two problems. First, I suspect you're using Visual Studio 6.0, in which case you should be aware that standard C++ says i is out of scope when you use it outside of the loop. To be correct, you should change your loop from this:

for(int i = 0; i<PROCESSORS; i++)

To this:

int i;

for(i = 0; i<PROCESSORS; i++)

Second, after the loop runs, i == PROCESSORS. That's likely going to be out of bounds for your array, so when you set max, you should store the current index in another variable and use that to print the title later.

Hi and thanks

Sorry my fault the int i was a mistake i had already been declared earlier. I can't get my head round how to display the match eg if my struct contained the following:
apples 12c
pears 6c
bananas 15c
pineapples 12c

then if i searched for max price it would return 15c AND bananas.

In my program it refuses to to return the matching element.

I am sure the problem is how i've coded the search, but I can't see how to fix it.

puzzled

Let your program remember the index i in another variable RemIndex for example.
Put an extra line between Line 8 and Line 9 : RemIndex = i;
In Line 14 do a cout of details[RemIndex].title instead of details.title.

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.