Unable to understand unexpected behaviour

I am confused why am I facing infinite loop in line 20.

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
#include <iostream>
#include<string.h>
#include<fstream>
using namespace std;
class book
{
    int bookid;
    char booktitle[30];
    float price;
public:
    void input()
    {
        static int i=0;int x;float z;
        while(i<=2)
        {
            if(i==0){cin>>x;}
            else if(i==2){cin>>z;}
        if(i==0 && x>=0){bookid=x;i++;break;} else {cout<<"invalid input"<<endl;continue;}
        if(i==1){cin.ignore();cin.getline(booktitle,30);i++;break;}
        else if(i==2 && z>=1){price=z;break;} else {cout<<"invalid input"<<endl;continue;}
        }
    }
    void getdata()
    {
    cout<<"Enter book id "<<endl;
    input();
    cout<<"Enter book title "<<endl;
    input();
    cout<<"Enter book price "<<endl;
    input();
    }

};
int main()
{
    book b1,b2;
    b1.getdata();
    return 0;
}
Last edited on
For the love of god, keep your code strictly at one statement per line or less. It's almost impossible to read like this. Lines 18-20 are particularly bad.

On line 18 you have a true and false block where one ends in break and the other in continue. Control flow must take either one or the other, there's no third choice, and both branches will cause control flow to not continue executing what follows the if, so lines 19 and 20 can't possibly execute. So if i is neither 0 nor 2, the false branch on line 18 will execute, and since there's nothing in that path that can change the value of i, the loop will never terminate.
Thanks a lot,
I will remember your advice,thanks again
Topic archived. No new replies allowed.