0

I use CLion, MinGW. When I want to write Cyrillic characters to a file, are written to the file \0, but in the console everything is fine. If I use windows-1251 encoding then everything is fine, but if I do cout << "Привет", in console will Привет

#include <iostream>
#include <fstream>
#include <windows.h>

using namespace std;

int main() {
    system("CHCP 65001 > nul");
    SetConsoleCP(CP_UTF8);
    SetConsoleOutputCP(CP_UTF8);

    fstream fileStream;

    fileStream.open("file.txt", ios_base::in | ios_base::out | ios_base::app);

    string message;
    cin >> message;

    fileStream << message << endl;

    fileStream.close();
}

enter image description here

man
  • 47
  • 4
  • Hard code the message with Cyrillic characters in the source code instead of reading them from the console. That way you can check if the problem is with reading or writing. At the moment I can't reproduce this, because I can't write Cyrillic. – Thomas Weller Aug 10 '23 at 11:33
  • "if I do cout << "Привет", in console will Привет" - so are you asking about a problem writing to the file or are you asking about a problem writing to the console? Focus on one question at a time. You will confuse yourself less. – Thomas Weller Aug 10 '23 at 11:36
  • 2
    Lots of variables that were not provided. Windows 7? 8? 10? 11? MinGW/bash shell? Terminal shell? PowerShell? CHCP setting? Font? You may find one-or-more relevant answers here: https://stackoverflow.com/a/45622802/4641116 – Eljay Aug 10 '23 at 11:39
  • Does this answer your question? [How do I properly use std::string on UTF-8 in C++?](https://stackoverflow.com/questions/50403342/how-do-i-properly-use-stdstring-on-utf-8-in-c) – Jan Schultke Aug 10 '23 at 11:49
  • If you do cout << "Привет" having your code editor utf-8 but target windows 1251 (single byte) stream then you of course get garbage in your stream. On the other hand getting utf-8 as cin >> message is impossible from windows 11 console. It just replaces all non-ascii symbols with nuls. – Öö Tiib Aug 10 '23 at 12:12
  • If your string is hard-coded in your code, you have to have the proper encoding everywhere (source file encoding, compiler options, correct setting for the console output and a recnt version of Windows that support UTF-8). And for the file, you need to ensure that UTF-8 encoding has been detected (if your don't une BOM) – Phil1970 Aug 10 '23 at 12:33
  • Not sure if MinGW standard library is handling localization properly. Many compilers standard library are poorly handling encoding and third party libraries (like boost) has to be used. Here is [MSVC demo how to handle encoding](https://stackoverflow.com/a/67819605/1387438) (works on that compiler, it doesn't work for example for apple clang). Note this can be extrapolated for MinGW make sure proper encoding is used in executable (probably it uses UTF-8 as default). – Marek R Aug 10 '23 at 13:43

0 Answers0