我想在窗口下使用 c++ 以某种基本方式表示西里尔字符

I want to represent a cyrillic character in some basic way using c++ under windows

本文关键字:方式 表示 字符 窗口 c++      更新时间:2023-10-16

所以我实际上正在尝试制作一个代码,将所有西里尔字母从一个单词转换为相关的拉丁字母。例如,俄语"я"应变为а"q"等。所以,现在我找到了我认为最好和最简单的西里尔符号处理方法,即:

#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
    const char *s = "яятя";     //my constant cyrillic char
    char c[10];                 //I'll transform it into that
    CharToOemA(s, c);           //the way I saw on the internet, I have barely understood what it actually does...
    cout << c << endl;          //This gives me the "яяяя" I need, so I'm happy...
    for(int i = 0; i < (int)strlen(c); i++)
    {
        //So I'm looping my character and want to somehow compare each single char with some kind of representation of the cyrillic "я"
        //Somehow using the encoding system of the c++ GNU compiler code blocks 13.12
        //Unicode number of "я" - U+044F
        if(c[i] == ...) //What could I use?
        //tried with 'u044F', but it didn't work
            cout << c[i] << " -- this should be a q!" << endl;
    }
    cout << "Press any key to continue..." << endl;
    cin.get();
    return 0;
}

我可以猜到这已经被回答了很多次,但我目前还没有找到最正确的方法来处理代码本身中那些该死的西里尔字符串和字符,比较它们并用它们做一些事情......所以如果你能提出一种方法来实现我的目标,我将不胜感激......

由于您还不太确定所需的输入编码,因此一个简单的入门方法是假设您的输入将使用 UTF-16。

由于您的编译器支持 C++11,我相信以下内容应该适合您:

#include <string>
#include <iostream>
int main() {
  std::u16string text = u"яятя";
  for (char16_t c : text)
  {
    if (c == u'я')
      std::cout << 'q';
    else
      std::cout << '?';
  }
  std::cout << std::endl;
  return 0;
}

您会注意到代码的以下更改:

  • 我正在使用 Unicode 字符串文字:яятя生成一个 UTF-16 字符串文字。有关其他选项,请参阅 cpp 首选项
  • 这意味着每个字符的长度为两个字节,因此我使用 std::u16string 来存储字符串,并使用 char16_t 数据类型来迭代字符

如果您最终想从文件等中读取 UTF-8 编码的文本,您可能需要在读取输入后从 UTF-8 转换为 UTF-16。C++标准的最现代版本和最现代的编译器支持如下转换函数:

std::wstring_convert<std::codecvt_utf8_utf16<char16_t>,char16_t> convert;
std::cout << "UTF-8 version: "
          << convert.to_bytes(text)
          << std::endl;

同样convert.from_bytes()从 UTF-8 转换为 UTF-16。但是您的编译器版本可能还不能正确支持此功能。