0

Part 2 on encoding characters in C++ (by User123).

<- Go to the previous post.

I was yesterday making some code, and Paul Sanders in this question told me useful solution: He told me not to use std::cout << "something"; but to use std::wcout << L"something";.

But I have another problem. Now I want to do something like this (some special characters, but in array):

#include <iostream>
using namespace std;
string myArray[2] = { "łŁšđřžőšě", "×÷¤ßł§ř~ú" };
int main()
{
    cout << myArray[0] << endl << myArray[1];
    return 0;
}

But now I get something really unusual:

│úÜ­°×§Üý
θĄ▀│ž°~˙

If I add L in front of the array, I get (Visual Studio 2019):

C++ initialization with '{...}' expected for aggregate object

How can I represent these special characters but in the array?

Community
  • 1
  • 1
User123
  • 476
  • 7
  • 22

1 Answers1

3
#include <iostream>
using namespace std;
wstring myArray[2] = { L"łŁšđřžőšě", L"×÷¤ßł§ř~ú" };
int main()
{
    wcout << myArray[0] << endl << myArray[1];
    return 0;
}

L can only be applied directly to string literals. The result is a string literal of type wchar_t[] (wide character) rather then the usual char_t[] (narrow character), so you cannot save it in a string. You need to save it in a wstring. And to output a wstring you need to pass it to wcout, not cout.

walnut
  • 21,629
  • 4
  • 23
  • 59
  • Doesn't work in Visual Studio 2019, Windows 7 Professional. There aren't any characters at all, just blank output. – User123 Mar 01 '20 at 10:24
  • @User123 But you are saying that `std::wcout << L"łŁšđřžőšě";` or something similar works? – walnut Mar 01 '20 at 10:28
  • Yes, but I need to specify ```#include #include ``` and then ```_setmode(_fileno(stdout), _O_U16TEXT);```. – User123 Mar 01 '20 at 10:31
  • @User123 Then do the same for this example and it should work. The details of how wide characters behave is implementation-defined. – walnut Mar 01 '20 at 10:32
  • I have a small problem: Data (array) is written in another file than main.cpp. – User123 Mar 01 '20 at 10:36
  • And how can I accept such special characters in wchar_t? – User123 Mar 01 '20 at 10:41
  • @User123 I don't see what the problem is. You do the setup with `#include #include ` and `_setmode(_fileno(stdout), _O_U16TEXT);` in `main` and then you can use wide character versions of all string-related tools as I mentioned in my answer. – walnut Mar 01 '20 at 10:44
  • Ok, I have solved the error, but now I can't accept special characters in ```wstring x; cin >> x;```. I get the error. C++ no operator matches these operands operand types are: std::istream >> std::wstring – User123 Mar 01 '20 at 10:46
  • 2
    @User123 Use `wcin` instead of `cin`. – walnut Mar 01 '20 at 10:47