How to write and read Cyrillic properly from file?

2019-08-12 18:38发布

问题:

I have the following code:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;
int main()
{
    string rus = "абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦШЩЪЫЬЭЮЯ";
    string lat = "abvgděëžzijklmnoprstufhcčšŝŭeûâABVGDĚËŽZIJKLMNOPRSTUFHCČŠŜŬEÛÂ";
    ifstream gdata("data.txt");
    if(!gdata){
        gdata.open("data.txt");
    }
    string temp;
    while(gdata){gdata >> temp;}
    gdata.close();
    ofstream sdata("data.txt", ios::out | ios::trunc);
    for(unsigned int i = 0; i < temp.length(); i++){
        int index = rus.find(temp[i]);
        if(index == -1){sdata << temp[i];}
            else{sdata << lat[index];}
    }
    sdata.close();
    return 0;
}

I would like to read Russian Cyrillic from a file. Then, program would find the index of each character in the string rus, and if it finds the character, then it finds the corresponding letter within lat string. This letter would then be written to the file. Unfortunately, when I type something into the file and then run the program, I get weird output such as @>A8 with random squares (not visible here for some reason). How can I make my program read the Cyrillic properly? I have already looked at over 10 questions here about similar subjects, but considering I'm very much a beginner in C++, nevermind encoding, I didn't understand the answers in the slightest, mainly as no example was provided that I could understand.

Also, even if most characters are latin and there is just one Cyrillic in the text, the entire text becomes malformed into random letters like @>A8

标签: c++ cyrillic