将字符串添加到另一个字符串

时间:2009-10-11 12:12:07

标签: c++ string

目前,我有这个代码将“标记”添加到异常消息中,这给我一个非常简单的堆栈跟踪版本:

try {
    doSomething();
} catch (std::exception& e) {
    int size = 8 + _tcslen(e.what());
    TCHAR* error = new TCHAR[size];
    _sntprintf(error, size, TEXT("myTag: %s"), e.what());
    std::exception x = std::exception(error);
    delete []error;
    throw x;
}

它看起来很可怕,我确信必须有一个简单的方法来实现这一目标。你能帮帮我吗?

4 个答案:

答案 0 :(得分:3)

这样的事情:

throw std::exception(std::string("myTag: ").append(e.what()).c_str());

添加了对c_str()的调用并在Visual Studio中对其进行了测试并且它可以工作(旁注:这不能在gcc中编译,实现中只有一个默认构造函数。)

答案 1 :(得分:3)

为什么不使用std :: string?

try {
    doSomething();
} catch (const std::exception& e)
{
    throw std::exception(std::string("myTag: ") + e.what());
}

其他说明: 据我所知,std :: exception没有这种形式的构造函数(只有它的子类才有)。

不确定您使用TCHAR缓冲区的原因。除了std::exception::what之外,char*可以返回任何内容吗?如果是这样,也许您可​​以使用std::basic_string<TCHAR>

要记住的重要事项:什么会返回const char*(无论出于何种原因)。例如,它仍然想知道10或13个字符消失在哪里:

throw some_exception(e.what() + '\n' + moreinfo);

答案 2 :(得分:0)

是的,有。

std::string S1="Hello",S2=" World";
S1+=S2;

答案 3 :(得分:0)

为什么不直接使用std::string。你可以做std::string s = std::string("myTag") + e.what()。如果你想要char *指针使用c_str()成员函数的字符串。

相关问题