Home > Net >  while loop doesn't loop in c
while loop doesn't loop in c

Time:11-03

So i just started C yesterday, I had a fair bit of java experience so that be the cause idk, I try to run this code and for some reason the while loop isn't looping, i tried changing the if break statement from ask==false to ask=false, that just ends up with an infinite loop without even taking user input.

Here's the code:

#include <iostream>
#include <math.h>
using namespace std;

int main(){
    double raduis;
    const double pi = 3.14;
    bool ask;
    
    while(true){
        cout << "Enter the raduis of the circle:"<< endl;
        cin >> raduis;
        double circ = 2*pi*raduis;
        double area = pi*pow(raduis,2);
        cout << "The Circumference of the circle is: "<< circ <<endl;
        cout << "The Area of the circle is: "<< area<<endl;
        cout <<"Would you like to run again?"<< endl;
        cin >> ask;
        if(ask==false){
            break;
        }
    }
}

I've tried changing the bool to a char value with "y" or "n" values but to no avail nothing works.

CodePudding user response:

Call clear on cin before the input and make sure the input is only 0 or 1,

From cppreference:

If the type of v is bool and boolalpha is not set, then if the value to be stored is ​0​, false is stored, if the value to be stored is 1, true is stored, for any other value std::ios_base::failbit is assigned to err and true is stored.

CodePudding user response:

There's nothing wrong with the code, you may wanna check the configuration of your IDE or your text editor, probably the C compiler is not loaded correctly.

  • Related