EDIT: It has been pointed out to me that I misread your loop’s termination condition. (Sorry, insomnia.)
Possible Answer 1
As I read it, you appear to want to repeatedly do something with positive values of height
, and terminate when an invalid value is given.
To make that happen, the correct thinking on this should be:
- Get a value
- If the value is zero, terminate the loop
- Else do stuff with the value
Hence:
while (true)
{
int height = get_int("Height: ");
if (height <= 0) break; // invalid height terminates loop
// use height here //
}
Possible Answer 2
If your desire is to repeatedly ask for a height until the user gives you a valid value in order to continue, then the only answer is to move the value declaration out of the loop, as anything declared local to the loop will not be usable outside of the loop:
int height;
do {
height = get_int("Height: ");
} while (height is not valid);
// use height here //
This is exactly as Luis Colorado explains, because he was awake enough to properly read your loop condition.
Useful stuff for C++ people finding this by title only
As I had previously misread the solution to terminate if height
becomes zero (a common semaphore for homework problems involving integers), and because C++ people will also find this answer, I had also given a C++ solution where the condition and body share locality as follows:
In current versions of C++ you can integrate the variable into the loop condition:
while (int height = get_int("Height: "))
{
// use height here //
}
I think this is true of C++11 or later, but it might have been introduced in C++14, IDK and don’t care to look it up. You should be using nothing less than C++17 these days...
This solution only works for variables that can be converted to truthy values — in this case, the loop terminates when height
is zero.
In OP’s particular case, this won’t work.
Now go vote for Mr Colorado’s answer, because it explains the locality problem better.