Home > Net >  C redefinition in while loop
C redefinition in while loop

Time:08-16

I'm trying to make a loop that asks coordinates from the user, and then prints those coordinates if they are in range of [1, 3]. If they are out of range, it prints error message. If input is 'q' it prints "Quitting".

I have defined x and y as int, but 'q' is char. How this kind of redefinition should be done?

#include <iostream>

using namespace std;

int main()
{
    int x; int y;

    while (true) {
    cout << "Enter coordinates (x, y): ";
    cin >> x >> y;

    if (x >= 1 && x <= 3 && y >= 1 && y <= 3) {
        cout << "Removing " << x << " " << y << endl;
    }
    else if (char x = 'q') {
        cout << "Quitting" << endl;
        break;    
    }
    else cout << "Out of board" << endl;
    }
}

CodePudding user response:

You define x of type char in your else if branch. Thus, you redefine the name x, which was previously defined as an int.

Avoid mixing char and int here. Try to use control characters, like passing an end-of-file to end the loop.

int x, y;
while (cin >> x >> y)
    // ...

Here, you test the input stream for validity on every iteration. It is done after both of the >> operators are evaluated and the std::cin is returned to be tested in the while's condition. And if, say, end-of-file was met, the iteration will end gracefully.

CodePudding user response:

You have a typo in

else if (char x = 'q')

It seems like you want to cast variable x to the char type and compare its value with 'q'. First, to cast a variable, the type needs to be in brackets, and secondly, the equality operator looks like ==, single = is an assigning operator. To do so, replace it with

else if ((char) x == 'q')
  • Related