C++ 如何在字符串中包含整数?

C++ 如何在字符串中包含整数?,c++,string,C++,String,如果系统调用失败,我想抛出一个异常,该异常包含与失败相关的“errno”。现在,我用这个: if (bind(...) == -1) { std::stringstream s; s << "Error:" << errno << " during bind"; throw std::runtime_error(s.str()); } if(绑定(…)=-1){ std::strings; sboost::lexical_cast在这种情况

如果系统调用失败,我想抛出一个异常,该异常包含与失败相关的“errno”。现在,我用这个:

if (bind(...) == -1) {
   std::stringstream s;
   s << "Error:" << errno << " during bind";
   throw std::runtime_error(s.str());
}
if(绑定(…)=-1){
std::strings;

s
boost::lexical_cast
在这种情况下很有用:

throw std::runtime_error("Error:" + boost::lexical_cast<std::string>(errno) + " during bind");
throw std::runtime_error(“error:+boost::lexical_cast(errno)+”在绑定期间);

我喜欢为此使用
boost::format

std::string msg = boost::str( boost::format("Error: %1% during bind") % errno );
throw std::runtime_error(msg);

一个警告是,如果catch块中有一个
bad\u alloc
,您可能会隐藏以前的错误。
boost::format
据我所知使用分配,因此可能会出现这种情况。您在这里没有捕获,因此它不完全适用。但在错误处理中需要注意这一点。

您可以编写own:

以下是一些提示:

class Exception{
public:
    Exception(const char* sourceFile, const char* sourceFunction, int sourceLine, Type type, const char* info = 0, ...);
protected:
    const char *mSourceFile;
    const char *mSourceFunction;
    int mSourceLine;
    Type mType;
    char mInfo[2048];
};
其中类型可以是:

enum Type
{
    UNSPECIFIED_ERROR,              //! Error cause unspecified.
    .. other types of error...  
};
所以你可以用通常的格式传递字符串

Exception(__FILE__, __FUNCTION__, __LINE__, Type::UNSPECIFIED_ERROR, "Error %d", myInt);

仅供参考,您可以使用来转换
errno
(并且只转换
errno
)你把两个问题混为一谈。你开始问如何引发异常,但后来你说真正的问题是如何在字符串中放入整数,所以我对你的问题进行了编辑,只问真正的问题。如果你仍然有问题,请另发一个问题,关于如何方便地抛出异常并附上错误信息I’我想知道这一点;这是与字符串格式不同的问题。如果你经常这样做,包装器肯定是有意义的。你不也需要检索错误值吗?@RobKennedy谢谢你的编辑。各位,谢谢strerror提到的。或者
抛出运行时错误(“错误:+std::to_string(errno));
(C++11)