tforste
tforste

Reputation: 43

C++ Reading in User Input without the commas

I'm currently working on a homework assignment for my C++ class to make a multi-player Tic-tac-toe game but I'm having trouble with the input part of the program (I've got almost everything else running).

Anyway, my goal is to prompt the current player for a row and a column in the format row,col. Then I need to place their mark in a two dimensional array that represents the game board.

I thought that I could simply read their input into a char array using cin and then take the 0 position and 2 position in that array and I would have my two numbers from their input. However, if I do this, I end up with the ASCII values of the input, not the number (for example, I get 49 instead of '1').

I feel like I'm probably overlooking something really simple, so any input would be very helpful and much appreciated. Here is what I had:

void getEntry(char XorO, char gameBoard[GRID_SIZE][GRID_SIZE])
{
    char entry[3];

    cout << XorO << " - enter row,col: ";
    cin >> entry;

    int row = entry[0];
    int col = entry[2];

    //Then I would use the row, col to pass the XorO value into the gameBoard
}

Upvotes: 2

Views: 1131

Answers (4)

Robᵩ
Robᵩ

Reputation: 168866

Let operator>> deal with interpreting the numbers:

void getEntry(char XorO, char gameBoard[GRID_SIZE][GRID_SIZE])
{
    int row, col;
    char comma;

    cout << XorO << " - enter row,col: ";
    std::cin >> row >> comma >> col; 

    if( (!std::cin) || (comma != ',') ) {
      std::cout << "Bogus input\n";
      return;
    }

    //Then I would use the row, col to pass the XorO value into the gameBoard
}

Upvotes: 1

Sameera Kumarasingha
Sameera Kumarasingha

Reputation: 2988

void getEntry(char XorO, char gameBoard[GRID_SIZE][GRID_SIZE])
{
    char entry[3];

    cout << XorO << " - enter row,col: ";
    cin >> entry;

    int row = entry[0] - '0';
    int col = entry[2] - '0';

    //if grid_size <= 9
}

Upvotes: 0

Code-Apprentice
Code-Apprentice

Reputation: 83577

Note that you are reading into a char array. When you convert the individual chars into ints, you will get the ASCII (or Unicode) values of the characters '0', '1', or '2', not the integer values 0, 1, or 2. To convert a single digit, you can use a useful property of ASCII codes: digit characters are sequential. This means that you can sutract the code for '0' from any digit to get the corresponding integer value. For example

row = entry[0] - '0';

Upvotes: 1

Jesus Ramos
Jesus Ramos

Reputation: 23266

To get the number just do

row = entry[0] - '0';
col = entry[2] - '0';

This will convert from ASCII to the actual digit.

Upvotes: 2

Related Questions