How to output two versions of a string, one with an escape character, and the other not, in C ++?

I have one chance to define a string, say

string s = "abc\"def\\hhh\"i";

After this definition, I want to output (using the stream to write to a text file) two versions of this line after that. The first is the sdefault output :

and "Protection \ HHH" I

The second one I want:

abv \ "Protection \\ HHH \" I

I am writing a kind of "recursive" definition, defining another line with extra escape characters is not a solution. I also looked at the raw string, but it can only output the second, not the C ++ 11 function, which is too useful for compiling some computers.

++ 11? ++ 11, ?

+4
2

​​:

std::string to_quoted(std::string const& src) {
    std::string result;
    result.reserve(src.size());  // Not necessary but makes the code more efficient (mentioned in comments)
    for (std::size_t i = 0; i < src.length(); i++) {
        switch (src[i]) {
        case '"': result += "\\""; break;
        case '\\': result += "\\\\"; break;
        // ...
        default: result += src[i];
        }
    }
    return result;
}

, , . , " ", , , , .

+4

- . , , - , , .

std::string, std::vector, , begin() end() ( ).

std::string , , , .

#include <iostream>
#include <string>
#include <iterator>

template< typename Range, typename OutputIterator >
OutputIterator copy_escaped( const Range& in, OutputIterator out ){
    for( const auto& c : in ){
        switch( c ){
            case '"': 
                *out++ = '\\';
                *out++ = '"';
                break;
            case '\\':
                *out++ = '\\';
                *out++ = '\\';
                break;
            case '\n':
                *out++ = '\\';
                *out++ = 'n';
                break;
            case '\r':
                *out++ = '\\';
                *out++ = 'r';
                break;
            case '\t':
                *out++ = '\\';
                *out++ = 't';
                break;
            // Could add more stuff to escape here
            // case ...:
            default:
                *out++ = c;
        }
    }
    return out;
}

, .

:

int main()
{
    std::string s = "abc\"def\\hhh\"i";

    // output normal
    std::cout << s << std::endl;

    // output escaped
    copy_escaped( s, std::ostream_iterator<char>( std::cout ) );
    std::cout << std::endl;

    // output escaped to other string
    std::string escaped_s;
    escaped_s.reserve( s.size() );  // not required but improves performance
    copy_escaped( s, back_inserter( escaped_s ) );
    std::cout << escaped_s << std::endl;
}

.

+2
source

Source: https://habr.com/ru/post/1671533/


All Articles