I try to output Russian letters in VC ++ 2017 to the console. Setlocale and chcp did not help, only _setmode (_fileno (stdout), _O_U16TEXT) helped; wcout << L "How many cars to put in the catalog?";

But now when I try to output a string, it throws some exception after the output "Here is your collection:". What is the problem? Here is the code:

#include <iostream> #include <string> #include <io.h> #include <fcntl.h> int main(void) { using namespace std; _setmode(_fileno(stdout), _O_U16TEXT); struct car { string name; int year; }; int qnt; wcout << L"Бколько Π°Π²Ρ‚ΠΎΠΌΠΎΠ±ΠΈΠ»Π΅ΠΉ ΠΏΠΎΠΌΠ΅ΡΡ‚ΠΈΡ‚ΡŒ Π² ΠΊΠ°Ρ‚Π°Π»ΠΎΠ³?"; cin >> qnt; car *cars = new car[qnt]; for (int i = 0; i < qnt; i++) { wcout << L"ΠΠ²Ρ‚ΠΎΠΌΠΎΠ±ΠΈΠ»ΡŒ #" << i + 1 << endl; cin.get(); wcout << L"Π’Π²Π΅Π΄ΠΈΡ‚Π΅ производитСля:"; getline(cin, cars[i].name); wcout << L"Π£ΠΊΠ°ΠΆΠΈΡ‚Π΅ Π³ΠΎΠ΄ выпуска:"; cin >> cars[i].year; } wcout << L"Π’ΠΎΡ‚ ваша коллСкция: " << endl; for (int i = 0; i < qnt; i++) { cout << cars[i].name << " "; cout << cars[i].year; } system("pause"); return 0; } 
  • It flies to cout year. comment out and see if it will work. - HasmikGaryaka
  • Put a breakpoint, after it step by step run, so see the reason. - HasmikGaryaka
  • @HasmikGaryaka turns with wcout to use wstring. I was wondering how are there any other ways to switch to UTF16 which supports many other characters except _setmode? with which I understand how to use wcout. - Alex.S
  • I managed to get the program working correctly. I wrote 2 lines. I will add to the answer - HasmikGaryaka
  • Everywhere write wcout, wcin. Year can be through cin cout, but better for uniformity like that. - HasmikGaryaka

1 answer 1

Announce

 wstring name 

For storing unicode, the usual is not suitable. And during the input also

 getline(wcin, cars[i].name); 

Instead of _setmode (_fileno (stdout), _O_U16TEXT);

  wcout.imbue(locale("rus_rus.866")); wcin.imbue(locale("rus_rus.866")); 
  • The advice about encoding 866 is not the best: some characters will inevitably disappear in single-byte encoding. - VladD
  • Does console support unicode? - HasmikGaryaka
  • Of course, supports. - VladD
  • Then give the answer more correct. Since in practice only this code works. - HasmikGaryaka
  • We have long had a canonical answer on this topic: ru.stackoverflow.com/a/459299/10105 - VladD