Search code examples
c++superscript

How to print superscript 3 in C++


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++?


Solution

  • 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:

    enter image description here

    If you can barely make out ³ getting printed above, let's zoom in closer:

    enter image description here

    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;
    }