Reputation: 67
I'm making a battleships game, so when I pass something such as "A10" into the coordinate function it needs to make column into letter and row into the number.
Coordinate(std::string coord = "A10")
{
char c = coord[0];
col = c - 16;
int r = atoi((coord.substr(1,2)).c_str());
row = r-1;
};
So in this example, passing A10 should make col = 0 (A=0,B=1,C=2) and row = 9.
The row equaling 9 seems to work but col equally 0 does not.
Upvotes: 0
Views: 621
Reputation: 457
The decimal value for A (0x41)
is 65
, so you'd get 49 with your current maths. col = c - 65
should give you the desired behaviour.
Upvotes: 0
Reputation: 12953
What you call character 'A' is just a funny name for the number 65 (its ASCII value).
According to this ASCII table, 'B' = 66, 'C' = 67 and so on. So what you should do is compute int column = static_cast<int>(coord[0] - 'A')
.
Upvotes: 0
Reputation: 6110
Are you trying to map the value of 'A' to zero? Remember that characters are single-byte integers,
char c = std::toupper( coord[0] );
if( c >= 'A' && c <= 'Z' )
{
col = c - 'A';
}
else
{
// TODO: Invalid/error?
}
Upvotes: 2