Specksynder
Specksynder

Reputation: 843

How do I include an integer in a string?

If a system call fails, I would like to throw an exception that contains the 'errno' relating to the failure. Right now, I use this:

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

That seems clumsy. I cannot directly append an integer to an std::string() - what is the best solution for this? Java has String().append(int), but there's no such facility in std::string. Does everyone write a wrapper around std::string for this purpose?

Upvotes: 2

Views: 202

Answers (3)

FailedDev
FailedDev

Reputation: 26930

You could write your own:

Here is some hints:

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

Where type could be:

enum Type
{
    UNSPECIFIED_ERROR,              //! Error cause unspecified.
    .. other types of error...  
};

So you can pass string in the usual format.. e.g.

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

Upvotes: 2

Tom Kerr
Tom Kerr

Reputation: 10720

I like using boost::format for this.

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

One caveat is that if you have a bad_alloc in a catch block, you might hide the previous error. boost::format uses allocations as far as I know, so it could suffer from this. You aren't catching here, so it doesn't exactly apply. It is something to be aware of with error handling though.

Upvotes: 3

hmjd
hmjd

Reputation: 121961

boost::lexical_cast is useful in this scenario:

throw std::runtime_error("Error:" + boost::lexical_cast<std::string>(errno) + " during bind");

Upvotes: 3

Related Questions