I am trying to use this function to test whether a boolean array is true at a coordinate the user selects. When it is true it runs the while loop over and over again until they finally put in coordinates that have not been used before.
It works fine if no cout statement is in it, but whenever I do put a cout statement in the while loop it infinitely runs the cout statement without letting me enter a new coordinate.
int const ROW = 4;
int const COL = 4;
void confirm(bool mask_array[ROW][COL],int &input1,int &input2);
int main() {
int row;
int coll;
bool mask[ROW][COL] = {
{true,true,true,true},
{true,true,true,true},
{true,true,true,true},
{true,true,true,true}
};
cout << "enter row: ";
cin >> row;
cout << "enter coullumn: ";
cin >> coll;
confirm(mask, row, coll);
}
void confirm(bool mask_array[ROW][COL],int &input1,int &input2) {
while (mask_array[input1][input2] == true )
cout << "enter again" << endl;
cin >> input1;
cin >> input2;
}
CodePudding user response:
The while loop is only going to execute a single statement unless you use braces { } to make a compound statement. In your example, only the cout is part of the loop; the cin statements are outside it.
while (mask_array[input1][input2] == true )
{
cout << "enter again" << endl;
cin >> input1;
cin >> input2;
}
CodePudding user response:
The condition in the loop below will be true as long as whatever is in mask_array[input1][input2] is not being converted to a boolean false:
while (mask_array[input1][input2] == true) cout << "enter again" << endl;
The value of 0 is converted to false - everything else is true.
The indentation of the following lines does not matter. A C compiler does not care about indentation. It'll execute the statement following the condition.
// this is what you check:
while (mask_array[input1][input2] == true ) cout << "enter again" << endl;
// not in the loop:
cin >> input1;
cin >> input2;
In while ( condition ) statement a compound statement must be surrounded by squiggly brackets, like in while ( condition ) { /* do stuff */ }. Everything within the squiggly brackets will then be executed repeatedly for as long as condition is (converted to) true.
To make that a proper "check-and-retry" loop:
for(unsigned y = 0; y < ROW; y) {
for(unsigned x = 0; x < COL; x) {
while ( !(std::cin >> mask_array[y][x]) ) {
std::cout << "enter again\n";
}
}
}
In this scenario, you could do with a helper function similar to the below:
int int_value_prompt(const char *prompt) {
int value;
std::cout << prompt;
while(!(std::cin >> value)) { // check if the extraction succeeded
if(std::cin.eof()) throw std::runtime_error("bye bye");
std::cin.clear(); // clear error state
std::cin.ignore(); // drop a char
std::cout << "try again\n" << prompt;
}
return value;
}
