如何动态创建转义序列?

How to dynamically create an escape sequence?

我正在尝试制作一个可以动态形成转义序列字符的程序。 请看下面我的代码。

void ofApp::keyPressed(int key){

    string escapeSeq;
    escapeSeq.push_back('\');
    escapeSeq.push_back((char)key);
    
    string text = "Hello" + escapeSeq + "World";
    cout << text << endl;
}

例如,如果我按 'n' 键,我希望它打印出来

Hello

World

但实际上打印出来了

Hello\nWorld

我怎样才能使程序运行?提前致谢!

您必须创建并维护一个查找 table,将转义序列映射到它们的实际字符代码。

字符串文字中的转义序列由编译器在编译时评估。因此,在代码中胡思乱想,试图在运行时创建它们,不会产生任何成果。所以你真的别无选择,只能按照以下方式行事:

void ofApp::keyPressed(int key){

    string escapeSeq;

    switch (key) {
    case 'n':
       escapeSeq.push_back('\n');
       break;
    case 'r':
       escapeSeq.push_back('\r');
       break;

    // Try to think of every escape sequence you wish to support
    // (there aren't really that many of them), and handle them
    // in the same fashion. 

    default:

       // Unknown sequence. Your original code would be as good
       // of a guess, as to what to do, as anything else...

       escapeSeq.push_back('\');
       escapeSeq.push_back((char)key);
    }

    string text = "Hello" + escapeSeq + "World";
    cout << text << endl;
}

这样的动态转义字符解析器,你还真得自己写。这是一个非常简单的版本:

char escape(char c)
{
    switch (c) {
    case 'b': return '\b';
    case 't': return '\t';
    case 'n': return '\n';
    case 'f': return '\f';
    case 'r': return '\r';
    // Add more cases here
    default: // perform some error handling
}