Program hangs, why? bit puzzled?

Hi all!

Trying to learn c++ using Pearsons C++ How to program book.

I'm currently stuck on this question from chapter 5. I have to use a sentinel value to end the loop and also use a switch statement inside the loop.
I typed up the following program but it keeps hanging at the end and I can't figure it out. Any help would be appreciated.

The program compiles without errors but when run it hangs after the sentinel value is typed in and fails to print out the final 'cout' statement. I've moved the statement within the loop to check it and it works but not outside the loop.

Any idea's what I'm not seeing?

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
// Fig 5.14: fig05_14.cpp
// Sentinal controlled loop with switch statement
#include <iostream>
#include <iomanip>
#include <math.h>

using namespace std;

int main()
{
    int productNumber = 0;
    int quantitySold = 0;
    int total = 0;
    
    while ( productNumber != -1)
    {
        cout << "Enter product number ( 1-5 ) and quantity sold, or -1 to quit: ";
        cin >> productNumber >> quantitySold;
           
        switch (productNumber)
        {
                case 1:
                total += quantitySold * 298; break;
                case 2:
                total += quantitySold * 450; break;
                case 3:
                total += quantitySold * 998; break;
                case 4:
                total += quantitySold * 449; break;
                case 5:
                total += quantitySold * 687; break;
                default:
                  cout << "Product code does not exist!"; break;
        }

    }
    
    cout << "Total cost of items: " << setprecision(2) << fixed
            << static_cast<double>(total)/100 << endl;
}


Its OK figured it out, it was the second cin variable waiting for an input? Duh!
Last edited on
Change this statement

cin >> productNumber >> quantitySold;

to

1
2
       cin >> productNumber;
       if ( productNumber != -1 ) cin >> quantitySold;



Or maybe it would be better to write

1
2
3
4
5
6
7
    while ( true )
    {
        cout << "Enter product number ( 1-5 ) and quantity sold, or -1 to quit: ";
        cin >> productNumber;
        if ( productNumber == -1 ) break;
        cin >> quantitySold;
        ....
Last edited on
Topic archived. No new replies allowed.