0

I'm new to C++, so sorry if this is obvious.

How can I get a character from a number? I have the following code:

for (int i = 0; i < 500; i++) {
    cout << i;
}

It's supposed to get the first 500 characters in the Unicode dictionary. I know that in javascript, it is String.fromCodePoint(i). What's the C++ equivalent?

phuclv
  • 37,963
  • 15
  • 156
  • 475
Spej
  • 31
  • 3
  • 6
  • Did you try `(char)i`? It won't do Unicode. C++ doesn't really know about Unicode. – user253751 Jul 23 '20 at 15:35
  • @user253751 it's not true. C++ isn't entirely Unicode-friendly, but it does have Unicode char and string types (`char8_t`, `char16_t`, `char32_t` and their corresponding `std::u8string`, `std::u32string` and `std::u32string`) – phuclv Jul 23 '20 at 15:53

1 Answers1

3

Use wchar_t instead

for (wchar_t i = 0; i < 500; i++) {
    wcout << i;
}

You can also use char16_t and char32_t if you're using C++11 or newer

However you still need a capable terminal and also need to set the correct codepage to get the expected output. On Linux it's quite straight forward but if you're using (an older) Windows it's much trickier. See Output unicode strings in Windows console app

phuclv
  • 37,963
  • 15
  • 156
  • 475
  • `wchar_t` is not Unicode, nor is it required to be interpreted as Unicode. – Nicol Bolas Jul 23 '20 at 15:47
  • @NicolBolas fair enough. But in practice it's UTF-16 on Windows and UTF-32 everywhere else. Besides **`char16_t` and `char32_t` are required to be UTF-16 and UTF-32 respectively** – phuclv Jul 23 '20 at 15:49
  • Don't you want to use [`wcout`](https://en.cppreference.com/w/cpp/io/cout) instead? – Mark Ransom Jul 23 '20 at 16:00
  • @MarkRansom yes, I forgot that. Thanks. Anyway I think std::cout on Windows has specializations for wchar_t – phuclv Jul 23 '20 at 16:06
  • 1
    @phuclv "*I think std::cout on Windows has specializations for wchar_t*" - no, it doesn't. That is why `std::wcin`/`std::wcout`/`std::wcerr` exist, to handle `wchar_t`. `std::cin`/`std::cout`/`std::cerr` handle `char` only. – Remy Lebeau Jul 23 '20 at 22:00