ending a while loop

closed account (9Nh5Djzh)
For class I need to make a program with a while loop that terminates when the user pushes ctrl d and then displays the data entered.
My problem is that when I push ctrl d the loop just starts running forever instead of stopping and displaying the next few lines of the program.

#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;

int main()
{
int maximum=0,minimum=0,sum=0;
int count=0.0;
float average, price;

while(price>0)
{


cout << " Enter the price of an asset: ";
cin >> price;

maximum=(price>maximum);

minimum=(price<minimum);
sum+=price;
++count;
}


average=(sum)/(count);


cout << "Their average is : " << average << endl
<< "Max number is : " << maximum << endl
<< "Min number is : " << minimum;
return 0;
}

Can anyone tell me what I need to do to make it work?
A couple issues.


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
using namespace std;

int main()
{
    int maximum=0,minimum=0,sum=0;
    int count=0.0;
    float average, price;     // you never intiliaze these. They could be anything..

    while(price>0)  //Can't guarantee this will even start looping at runtime. see above
    {

        cout << " Enter the price of an asset: ";
        cin >> price; 

       maximum=(price>maximum); //price > maximum will return a boolean value. Prolly not what you want. Use something like std::max.

       minimum=(price<minimum); //use something like std::min
       sum+=price;
       ++count;
    }

    average=(sum)/(count);

    cout << "Their average is : " << average << endl
    << "Max number is : " << maximum << endl
    << "Min number is : " << minimum;
    return 0;
}


I would rewrite it like this... (pseudo code)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//intial values
int max=0,min=0,count=0;
float average=0,price=0;
bool endLoop = false;

while (endLoop == false){
    //get the price, do your calculations, etc..
    if (isSomeKeyDown("Control-D") == true{
        endLoop = true;
    }
}

//calculate your average & print your stuff.
return 0;


Not sure how you want to check for user input. isSomekeyDown() I just made up you might need to google around for how to check key presses.
Topic archived. No new replies allowed.