Handling Non-Ascii Chars in C++

前端 未结 2 742
予麋鹿
予麋鹿 2021-01-01 04:40

I am facing some issues with non-Ascii chars in C++. I have one file containg non-ascii chars which I am reading in C++ via file Handling. After reading the file(say 1.txt)

2条回答
  •  没有蜡笔的小新
    2021-01-01 05:36

    At least if I understand what you're after, I'd do something like this:

    #include 
    #include 
    #include 
    #include 
    #include 
    
    std::string to_hex(char ch) {
        std::ostringstream b;
        b << "\\x" << std::setfill('0') << std::setw(2) << std::setprecision(2)
            << std::hex << static_cast(ch & 0xff);
        return b.str();
    }
    
    int main(){
        // for test purposes, we'll use a stringstream for input
        std::stringstream infile("normal stuff. weird stuff:\x01\xee:back to normal");
    
        infile << std::noskipws;
    
        // copy input to output, converting non-ASCII to hex:
        std::transform(std::istream_iterator(infile),
            std::istream_iterator(),
            std::ostream_iterator(std::cout),
            [](char ch) {
                return (ch >= ' ') && (ch < 127) ?
                    std::string(1, ch) :
                    to_hex(ch);
        });
    }
    

提交回复
热议问题