mercredi 22 janvier 2020

C++ Why does this else if run after the if is true

using namespace std;
int main(){
    int userinp=-1,dig1=0,dig2=0,dig3=0,dig4=0;
    while(userinp!=0) {
        cin>>userinp;
        if (userinp=0) userinp=0;
        else if(userinp<0||userinp>9999) cout<<"Wrong input";
        else if (userinp<10) { dig1++; userinp =-1;}
        else if (userinp<100) {dig2++; userinp =-1;}
        else if (userinp<1000) {dig3++; userinp =-1;}
        else {dig4++; userinp =-1;}
    }
    cout<<dig1<<endl<<dig2<<endl<<dig3<<endl<<dig4;
    return 0;
    }

I'm trying an exercise from my school book but it gets stuck in an infinite loop because it runs the else if userinp<10 when I type in 0. Why? If I delete the parts after the if goes out of the while.

Aucun commentaire:

Enregistrer un commentaire