2017-02-09 36 views
2

我想製作一個可以動態形成轉義序列字符的程序。 請看下面我的代碼。如何動態創建轉義序列?

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

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

回答

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

你必須自己編寫這樣一個動態轉義字符解析器。這裏有一個非常簡單的版本:

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 
}