Special characters in the console
In this example, I will use special characters from the Polish alphabet, but this rule applies to, e.g., the German ones, too. These signs aren't casually displayed in the console, but every one has their numerical representation. In the main()
function below, we can see that if we type a Polish letter while running the program, we will get a different numerical value than when we type it right away in the code (the console has a different encryption system). When writing with Polish characters, we can use a function to filter these characters from the text and change their numerical ASCII values to ones that display correctly in the console (and then display the whole corrected string).
In the example below, the characters
string contains all the Polish special characters, and the polish_characters
array contains their assigned numbers (they are in the same order). The pl
function will make a second array of numbers (the other ones), and the pl2
function will change the numerical values of the Polish characters from the string to those that display correctly.
#include <iostream>
using namespace std;
const string characters = "ąĄśŚźŹłŁóżŻńŃęĘćĆÓ";
int * pl(string characters) {
int *a = new int[characters.length()]; // we don't release the memory after this because it will be used later in the code
for (int i = 0; i < characters.length(); i++)
a[i] = static_cast<int>(characters[i]);
return &a[0];
}
int *polish = pl(characters);
int polish_characters[] = {-91, -92, -104, -105, -85, -115, -120, -99, -94, -66, -67, -28, -29, -87, -88, -122, -113, -32};
string pl2(string text) {
for (int i = 0; i < text.length(); i++) {
for (int j = 0; j < characters.length(); j++) {
if (text[i] == polish[j]) {
text[i] = polish_characters[j];
break;
}
}
}
return text;
}
int main() {
char x;
cin >> x;
cout << static_cast<int>(x) << endl; // ą = -91
cout << static_cast<int>('ą') << endl; // ą = -71
cout << pl2("afhdrgfdąśłÓśćĄĆ") << endl;
return 0;
}