Max Number Problem

I wrote a min/max program differently this time using a string to number conversion just to try something different. Anyway, the sum & min statements appear to work but the max part doesn't work. Where is my problem? How can I fix it? Thanks.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main()
{
    string value;
    int num;
    int sum = 0;
    int min;
    int max;

    for (int i=1; i<=5; i++)
    {
    cout<<"Enter value "<<i<<": ";
    cin>>value;

    if (!(istringstream(value) >> num)) num = 0;

    if (num < min)
        {
        min = num;
        }

    if (num > max)
        {
        max = num;
        }

    sum += num;
    }

    cout<<"Sum= "<<sum<<endl;
    cout<<"Min= "<<min<<endl;
    cout<<"Max= "<<max<<endl;

    return 0;
}
Try initializing min and max:
1
2
3
4
#include <climits>
//etc...    
    int min(INT_MAX);  // min to the maximum signed integer value (0x7fffffff)
    int max(INT_MIN);  // max to the minimum signed integer value (0x80000000) 
Thanks for the reply histrungalot! When I tried the INT_MIN & INT_MAX, both the min & max went bonkers. When I initialized with max=min=num;, both the min & max picked up the last entry.

The string to number conversion doesn't work too well right now compared to just using a straight number in the first place. My other min/max programs work properly unlike this one. I hoping that someone might have a solution to this problem. Thanks again!
I think I've solved the problem but it's kind of weird. I initialized max = 0 & left min uninitialized. That seem to make it work now.
When I tried the INT_MIN & INT_MAX, both the min & max went bonkers.

Did you get them the right way around?

Initial value of max should be INT_MIN and vice versa.

(As correctly stated by histrungalot).
You're both right! I had them reversed. It works properly now! I need to get new glasses or something. Thanks! :)
Topic archived. No new replies allowed.