如何动态创建转义序列?

Zac*_*Lee 2 c++ escaping character sequence

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

void ofApp::keyPressed(int key){

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

    string text = "Hello" + escapeSeq + "World";
    cout << text << endl;
}
Run Code Online (Sandbox Code Playgroud)

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

你好

世界

但它确实打印出来了

你好\nWorld

如何使程序运行?提前致谢!

Sam*_*hik 5

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

编译器在编译时评估字符串文字中的转义序列.因此,尽量使用代码,尝试在运行时创建它们,不会产生任何效率.所以你别无选择,只能做一些事情:

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;
}
Run Code Online (Sandbox Code Playgroud)