2

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.

Edit: Okay so I've solved the problem, as per @zdf 's suggestion I entered cin >> boolalpha >> ask; and it works perfectly now.

4
  • 2
    what is your input ? Commented Nov 3, 2022 at 9:28
  • Edit comment: you can use single backticks for inline code i.e. `false` gives false. The triple backtics for blocks of code need to be on a new line. Commented Nov 3, 2022 at 9:31
  • 2
    (1) Try this: std::cin >> std::boolalpha >> ask. You probably entered true. (2) You can use if (ask).... Commented Nov 3, 2022 at 9:32
  • Similar: stackoverflow.com/questions/26203441/cin-and-boolean-input Commented Nov 3, 2022 at 9:35

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Note that e.g. Scanner and Boolean.parse(String) in Java are more permissive if I'm not mistaken, so this may indeed be a problem introduced by a change of runtime.
@MaartenBodewes what ? This question is about C++ not Java
@463035818_is_not_a_number Literally on the first line: "So i just started C++ yesterday, I had a fair bit of java experience so that be the cause idk".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.