-2

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;
    }
}
  • 1
    Replace `x = 'q'` with `x == 'q'` and remove `char x = 'q'`. That is, you have a **typo**. – Jason Aug 16 '22 at 07:58
  • 1
    You can't. `cin >> x >> y;` will fail if the input is not an integer, and since you're not checking for errors it will go unnoticed. `while (cin >> x >> y) { ... }` would keep going while integers were entered and exit the loop if a character or EOF was entered. Another way is to perform all of the input into strings and parse them or check for "q". – Retired Ninja Aug 16 '22 at 07:58

2 Answers2

0

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')
0

A much simpler approach would simply ask the user to enter "q" in a separate prompt. You're asking for input into an int:

int x; int y;
cin >> x >> y;

And then checking if the user entered a char i.e. 'q' :

else if (char x == 'q') // == for comparison

What you can do is use a temporary variable to initially store x as a char, check if it is q and then move on:

    char tempX;
    cin >> tempX;
    if ( tempX == 'q' ) {
        cout << "Quitting" << endl;
        break;  
    }
    x = tempX - '0'; // for converting tempX to an int.
    cin >> y;

For more on the char conversion, you can read here.

sherxyar
  • 83
  • 6