簡體   English   中英

如何動態創建轉義序列?

[英]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'鍵,我希望它打印出來

你好

世界

但它確實打印出來了

你好\\ nWorld

如何使程序運行? 提前致謝!

您必須創建並維護一個查找表,該表將轉義序列映射到它們的實際字符代碼。

編譯器在編譯時評估字符串文字中的轉義序列。 因此,盡量使用代碼,嘗試在運行時創建它們,不會產生任何效率。 所以你別無選擇,只能做一些事情:

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM