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?

2
  • Did you try (char)i? It won't do Unicode. C++ doesn't really know about Unicode. Commented Jul 23, 2020 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) Commented Jul 23, 2020 at 15:53

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

5 Comments

wchar_t is not Unicode, nor is it required to be interpreted as Unicode.
@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
Don't you want to use wcout instead?
@MarkRansom yes, I forgot that. Thanks. Anyway I think std::cout on Windows has specializations for wchar_t
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.