I was wondering how you could print coloured text in a cross platform manner in C. I have looked at all the other answers on the forum, but none of them work during my testing (on Windows). For C , I have the working code in Fig 1, however when converting the code to C and assigning the strings to a variable I get the error \u001b is not a valid universal character
(Fig 2).
Fig 1
namespace Fore {
const std::string BLACK = "\u001b[30m";
// Rest of code is not included since it is just a repetition of the above code with background and style ANSI codes as well.
Fig 2
Image here since I don't have enough reputation to embed images yet.
CodePudding user response:
C and C have different rules for "universal character names" (UCNs), which is the official name for \u
and \U
sequences. (They're not the same as "escape sequences" because UCNs can be used outside quoted literals, for example in identifier names.)
In C, the rule is:
A universal character name shall not designate a code point where the hexadecimal value is:
- less than 00A0 other than 0024 (
$
), 0040 (@
), or 0060 (`
);- in the range D800 through DFFF inclusive; or
- greater than 10FFFF82)
So in C, you can't use UCNs for control characters, which is what the error message is telling you.
C is more generous; it allows you to use UCNs for control characters and other characters with small codepoints, but only inside string and character literals. (C also prohibits surrogate codepoints and excessively large codes, the second and third points in the above list.)
Both C and C allow you to use octal escape sequences (\033
) or hexadecimal escapes sequences (\x1B
). I'd personally recommend the latter, but \033
is common because hexadecimal escapes were not in the very earliest versions of C, and so \033
became a common idiom.
None of this is really platform-independent. Lots of platforms have consoles which don't interpret ANSI style codes.