How to write and read Cyrillic properly from file?

别等时光非礼了梦想. 提交于 2019-12-11 11:06:14

问题


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

来源:https://stackoverflow.com/questions/36121766/how-to-write-and-read-cyrillic-properly-from-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!