I am looking for a way to print superscript 3, I googled a lot and I found a way to print superscript 2:
const char expo_square = 253;
void main () {
std::cout << expo_square;
return;
}
After some more googling, I came across the Alt Keycode for superscript 3, which is:
Alt 0179
The problem with this is that while compiling the C source file:
const char expo_cube = 0179;
void main () {
std::cout << expo_cube;
return;
}
I get an error:
3d.cpp(18): error C2041: illegal digit '9' for base '8'
(don't mind the file name)
So I tried the next logical thing, since the Alt Keycode for superscript 2 is 253, I tried Alt Keycode 254, but all I ended up getting was:
■
So I wanted to ask:
How can I print superscript 3 in C ?
CodePudding user response:
Unicode superscript 3, or ³ is \u00b3 in utf-16 and \xc2\xb3 in UTF-8.
Hence, this would work with cout, assuming your console is UTF8.
#include <iostream>
int main()
{
std::cout << "\xc2\xb3" << std::endl;
return 0;
}
To set your console in UTF-8 mode, you can do it in a number of ways, each is OS dependent, if needed at all. On Windows, you can run chcp 65001 from the command prompt before invoking your code:
If you can barely make out ³ getting printed above, let's zoom in closer:
Alternatively, you can do this in code via a Windows API, SetConsoleOutputCP
SetConsoleOutputCP(65001);
So this works as well from a Windows program without having to do any environment changes before running the program.
#include <windows.h>
#include <iostream>
int main()
{
SetConsoleOutputCP(65001);
std::cout << "\xc2\xb3" << std::endl;
return 0;
}
CodePudding user response:
If you prefix the expression with a 0, the compiler considers this value to be represented in the octal radix. Values in octal radix must be in the range of [0,7]. The value 9 in the 0179 expression is outside of the octal radix range.
Try the following solution to print superscript 3:
std::cout << "x\u00b3" << std::endl;
The result: x3
References
CodePudding user response:
Expanding on the question- and answer scopes this function can be used to get superscripts for any power (may be useful to someone):
std::string supow(int pow)
{
std::string r{}, t{};
if (pow<0) { r="\u207b"; pow*=-1; } else r.clear();
t=itoa(pow); //stringize the pow for easier access to digits
for (auto c:t)
{
switch(c-48)
{
case 0: r ="\u2070"; break;
case 1: r ="\u00b9"; break;
case 2: r ="\u00b2"; break;
case 3: r ="\u00b3"; break;
case 4: r ="\u2074"; break;
case 5: r ="\u2075"; break;
case 6: r ="\u2076"; break;
case 7: r ="\u2077"; break;
case 8: r ="\u2078"; break;
case 9: r ="\u2079"; break;
}
}
return r;
}


