简体   繁体   中英

converting a char variable in an array to an int C++

I have an array ( char location[2]; ) This needs to receive two values from the user. The first is a letter the other a number, in that order. This is used to select a location in a 9 x 9 grid.

The grid appears

  A B C D E F G H I
1
2
3
4
5
6
7
8
9

When I try to store the second value as an int, The method I would think would work is being set to -48.

int row = location[1] - 48;

48 is the ASCII value of '1'. Shouldn't this have created an int with the value of one less than whatever number was input by the user? '2' (aka 49) - 48 = 1? It always comes out as -48 no matter what the input is.

My full function:

#include <iostream>
using namespace std;

void getLocation(int &column, int &row)
{
   int row = 0;
   int column = 0;
   char location[2];
   cout << "location: ";
   cin.getline(location,2);
   cin.ignore();
   cin.clear();
   switch (location[0])
   {
      case 'A':
         cout << "case A\n";
         column = 0;
         break;
      case 'B':
         cout << "case B\n";
         column = 1;
         break;
      case 'C':
         cout << "case C\n";
         column = 1;
         break;
   }
   row = location[1] - 48;
   cout << "column: "
        << column
        << " row: "
        << row
        << "\n";
}

location[1] - 48 will always be -48 if positive-length string is given because terminating null-character will be stored there. Allocate enough length to store the input. You are using C++, so using std::string is better to store strings than using arrays of char .

cin.getline(location,2) does not behave in the way you expect.

It writes a nul-terminated string to location ie location[0] is read from cin , and location[1] receives a character with value of 0 (numeric zero, not '0' ).

0 - 48 always produces a result of -48 as an int .

Note, also, that '1' is not guaranteed to have a value of 48 . '0' does in ASCII and compatible character sets. Other character sets will give different values.

You would be better off using std::string - that eliminates the need to worry about arrays of char and nul termination.

The size of the stream for cin.getline needs space for a null terminator. Therefore, increase the size of the stream buffer and terminate input on the carriage return:

cin.getline(location, 3, '\r');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM