问题
for the following function
void display()
{
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (board[i][j] < 84 && (i+j)%2 == 0)
SetConsoleTextAttribute( GetStdHandle( STD_OUTPUT_HANDLE ), 0x70);
else if (board[i][j] < 84 && (i+j)%2 == 1)
SetConsoleTextAttribute( GetStdHandle( STD_OUTPUT_HANDLE ), 0xc0);
else if (board[i][j] > 97 && (i+j)%2 == 0)
SetConsoleTextAttribute( GetStdHandle( STD_OUTPUT_HANDLE ), 0x7c);
else if (board[i][j] > 97 && (i+j)%2 == 1)
SetConsoleTextAttribute( GetStdHandle( STD_OUTPUT_HANDLE ), 0xc7);
cout << " " << toupper(board[i][j]) << " ";
}
cout << endl;
}
}
instead of returning chars for the char board[8][8] it returns integers so my output looks like
82 78 66 81 75 66 78 82
80 80 80 80 80 80 80 80
32 32 32 32 32 32 32 32
32 32 32 32 32 32 32 32
32 32 32 32 32 32 32 32
32 32 32 32 32 32 32 32
80 80 80 80 80 80 80 80
82 78 66 81 75 66 78 82
rather than the expected output of
R N B Q K B N R
P P P P P P P P
P P P P P P P P
R N B Q K B N R
I have also tried declaring a char a = board[i][j]; cout << toupper(a); in an attempt to confirm the variable type as a character and received the same output.
this is an assignment for a class so i don't expect much help, i just want to know why my function is returning integers in place of chars so that i know what my mistake is for future reference, Google didn't help much. is it some sort of scope issue with toupper?
回答1:
Toupper function returns the uppercase equivalent to c, if such value exists, or c (unchanged) otherwise. The value is returned as an int value that can be implicitly casted to char.
http://www.cplusplus.com/reference/cctype/toupper/
回答2:
The intention for toupper is that it can work in other languages than English, and hence it would have to support input and output which is larger than the 8 bit char
, and therefor should return something which can be transformed into a unicode or UTF-character.
Simply just casting it to char
is probably a source of buggy code for later on depending on what the purpose of your software is.
Have a look at this question on how to use it for wide characters and unicode.
Convert a unicode String In C++ To Upper Case
回答3:
The documentation is clear : http://www.cplusplus.com/reference/cctype/toupper/
int toupper ( int c );
So you just have to cast to char
:
cout << " " << (char) toupper(board[i][j]) << " ";
回答4:
You need to use cout << char(toupper(board[i][j]));
to work around the goofy return type of toupper.
来源:https://stackoverflow.com/questions/25963248/toupper-returns-integer-rather-than-char