user2108147
user2108147

Reputation: 21

C++ Exiting a loop from a certain key hit

So I have this function in my class that reads in these three variables until numSale equals 10, or else until "X" is entered. Currently, I can run this, but it does not exit. Any advice on how to make the loop quit if X is hit?

void Read()
   {
      string id;
      float  price;
      float  amount;

      cout << "Please enter your product id, unit price and amount of unit "
           << endl << "[id price amount] and enter X to finish:" << endl;
      // DO_5: use a while loop to read in sales objects to saleRecord array
     cin >> id >> price >> amount;
      while(id != "X" || numSale < MAX_RECORDS)
     {
        Sale sales(id, price, amount);
        saleRecord[numSale] = sales;
        ++numSale;
        cin >> id >> price >> amount;
     }

Upvotes: 0

Views: 1827

Answers (3)

How are you testing the exit? Could it be the case that cin >> id >> price >> amount is blocking waiting for a price and an amount?

In other words, if the user just enters

X <Enter>

Your program will still stay on the cin line until it finds two more inputs that it can parse as floats.

Upvotes: 0

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153955

The easiest way is to start off with checking that you stream is in good state. You want to check our input after reading it anyway:

while (numSale < MAX_RECORDS && std::cin >> id >> price >> amount && id != "X") {
    // do something with the input
}

Upvotes: 0

Bart Friederichs
Bart Friederichs

Reputation: 33531

Change this:

while(id != "X" || numSale < MAX_RECORDS)

into this:

while(id != "X" && numSale < MAX_RECORDS)

A while loop keeps running as long as the expression inside it is true.

Upvotes: 4

Related Questions