Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
544 views
in Technique[技术] by (71.8m points)

C++ 如何从将遍历带中文的字符串呢?

我现在需要从一个 utf-8 文件中读取文本内容,然后将文件内容读入到 std::string中。
但是由于 u8 中文字符的长度是不定的,处理起来相当麻烦,而且还要区分 带 bom 的和不带 bom 的文件。

请问也没有更简单一点的,遍历带中文字符串的方法呢?即使是用宽字符看起来也没有用,而且 cout u8 字符串的时候,在 chcp 936 下还会乱码。。。

我目前只处理了三个字节长度的中文,而代码已经很长了:

void output(char ch, bool r = false){
    // 缓存 3 个字节再输出
    // r 代表逆序传入字符
    static char hans[3];
    static char bom[3]{
            (char )0xef,(char)0xbb, (char)0xbf
    };
    static char rbom[3]{
            (char)0xbf, (char)(0xbb), (char)0xef
    };
    if(r){
        static int num = 2;
        hans[num] = ch;
        --num;
        if( !num ){ // 当 num 为0时
            if( strcmp(hans, rbom) ) // 当字符串与 bom 不同时
            {
                if( (int)hans[2] >= 0x80 ){
                    swap(hans[0], hans[2]);
                    cout<<hans;
                }
                num = 2;
            }
        }
    }else{
        static int num = 0;
        hans[num] = ch;
        ++num;
        if( num == 2){
            if( strcmp(hans, bom) ) // 当 字符串与 bom 不同时
                cout<<hans;
            num = 0;
        }

    }
}

附带一些有关链接


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...