Phone Database Program - Infinite Loop

Continuing on my program, I still seem to hit another snag. I am trying to only allow the user to only input 4 characters as the ProductID. It works. However, when I try to put more than 4, it creates an infinite loop for this:

"Please enter the price for the phone."
and I can't continue. What is going on.

Some of my code is below:

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
while (!cin>> n )
    {   cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
     cout<<"Invalid input. Please try again."<<endl;
     cout<<endl;
     cout<<"How much info do you need to enter?"<<endl;
     cin>>n;
    cout<<endl;
    }


for (int c=0; c<n; c++)
{
    cout<< "What is the name of your phone?"<<endl;
    cin>> name[c];
                          cout<< "Please enter the product ID."<<endl;

                        cin>> setw(5) >> productID[c];
                        if(strlen(productID[c]) > 4) {
                            for(int b=0; b<4; b++) {
                                if(!std::isalpha(productID[c][b])) {
                                    cout<<"It has to be four characters."<<endl;
                                    cin>> productID[b];
                                }   }
                        }
                        cout<<endl;

       cout<<"Please enter the price for the phone."<<endl;
        cin>>price[c];
                cout<<endl;

        while(price[c]<0)
            {
        cout<<"Please put in a price larger than 0."<<endl;
            cin>>price[c];
                cout<<endl;
                }
Last edited on
The issue probably has to do with the remaining input sticking around in the buffer and trying to be inserted into the next read function, which is cin>>price[c] (line 29 above as you indicate).

Basically, price[c] is an integer/float/double type, but you are trying to shove character types into it, and cin doesn't know how to deal with that (undefined behavior), so it freaks out.

Give the user an error message asking for a correct-sized input for productID (you tried to do so on lines 19 and 20, but got reverse signs going on so it's not corrected), and/or parse the inputs to price[c] from a string first to ensure that what is read really is an integer.

I'd suggest the latter (doing your own type-checking on number types), because this same issue would happen if the user accidentally hit a cama instead of a period when inputting for price[c].
Last edited on
Registered users can post here. Sign in or register to post.