gpt4 book ai didi

c++ - 如何动态创建转义序列?

转载 作者:太空狗 更新时间:2023-10-29 23:49:23 25 4
gpt4 key购买 nike

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

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

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

最佳答案

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

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

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

关于c++ - 如何动态创建转义序列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42126598/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com