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

void ofApp::keyPressed(int key){

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

    string text = "Hello" + escapeSeq + "World";
    cout << text << endl;
}
例如,如果我按'n'键,我希望它能打印出来

但实际上打印出来

如何使程序正常工作?提前致谢!

最佳答案

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

字符串文字中的转义序列在编译时由编译器求值。这样,单调地尝试在运行时创建代码并不会产生任何成果。因此,您除了别无选择,实际上别无选择:

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;
}

10-08 17:40