微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 C++ 读取/打印非 ASCII 字符

如何解决使用 C++ 读取/打印非 ASCII 字符

如何读取和打印这个数组的第一个字符? (不是整个字符串,只有第一个字符)。

char data[]= "£A";
printf("%c",data[0]);  

在这里,我试过了 printf("%c",data[2]);

输出:A

但是 printf("%c",data[0]);printf("%c",data[1]); 不打印任何内容(空白输出)。

解决方法

代码

#include <cstring>
#include <string>
#include <stdexcept>
#include <iostream>

typedef std::string String;

size_t GetTotalUTF8Chars(const String &data)
{
    size_t ret = 0;
    for (char value : data)
    {
        if ((value & 0xc0) != 0x80)
        {
            ++ret;
        }
    }
    return ret;
}

String GetUTF8Char(String data,size_t pos)
{
    if(pos >= GetTotalUTF8Chars(data))
    {
        throw std::length_error(u8"Invalid UTF8 character position");
    }
    String result;
    String::const_iterator it = data.begin();
    String::const_iterator beginIterator(it);
    size_t utf8pos = 0;
    if ((data[0] & 0xc0) != 0x80)
    {
        it++;
    }
    while (it != data.end())
    {
        char value = *it;
        if ((value & 0xc0) != 0x80)
        {
            if (pos == utf8pos)
            {
                return String(beginIterator,it);
            }
            beginIterator = it;
            utf8pos += 1;
        }
        it++;
    }
    return String(beginIterator,it);   
}

int main()
{
    char cstr[] = u8"Hello??World?£A";
    String str = String(cstr);

    std::cout<<"█ With C String"<<std::endl;
    for (size_t i = 0; i < GetTotalUTF8Chars(cstr); i++)
    {
        std::cout << i <<".- " << GetUTF8Char(cstr,i) << std::endl;
    }

    std::cout<<"█ With C++ String"<<std::endl;
    for (size_t i = 0; i < GetTotalUTF8Chars(str); i++)
    {
        std::cout << i <<".- " << GetUTF8Char(str,i) << std::endl;
    }

  str = u8"£A";
    printf(u8"Position0 = %s / Position1 = %s\n",GetUTF8Char(str,0).c_str(),1).c_str());

  try{
    std::cout << GetUTF8Char(str,15) << std::endl; 
  }
  catch(std::exception &ex)
  {
    std::cout<< "Exception message:" <<ex.what()<<std::endl;
  }

    return EXIT_SUCCESS;
}

输出

█ With C String
0.- H
1.- e
2.- l
3.- l
4.- o
5.- ?
6.- ?
7.- W
8.- o
9.- r
10.- l
11.- d
12.- ?
13.- £
14.- A
█ With C++ String
0.- H
1.- e
2.- l
3.- l
4.- o
5.- ?
6.- ?
7.- W
8.- o
9.- r
10.- l
11.- d
12.- ?
13.- £
14.- A
Position0 = £ / Position1 = A
Exception message:Invalid UTF8 character position

你的例子

str = u8"£A";
printf(u8"%s\n",0).c_str());
printf(u8"%s\n",1).c_str());
printf(u8"%s %s\n",1).c_str());

输出

£
A
£ A

你可以试试这个代码 Get UTF8 Char(https://repl.it/@JomaCorpFX/Get-UTF8-char#main.cpp)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。