【问题标题】:syslog const char* to stringsyslog const char* 到字符串
【发布时间】:2010-11-14 08:24:09
【问题描述】:
   catch (exception e) { syslog (LOG_ERR, "exception: " + e.what());    }

这是我想要做的,但它不起作用,我试过用这个

string ctos(const char& c){

    stringstream s;
    s << c;

    return s.str();
}

但还是输了

任何帮助将不胜感激。

【问题讨论】:

  • 您是否尝试将const char*(根据您的问题)或const char(通过引用传递,根据您的代码)转换为string?您的用法不清楚。
  • 虽然它与问题无关,但我建议在catch 中使用const exception&amp; e,否则您的异常对象将被截断为exception
  • 安全注意事项:作为一般规则,仅在 printf 或 syslog 类型格式字符串中使用字符串文字。如果是变量,则将其作为参数传递。在这个例子中,如果有人这样做:throw std::runtime_error( std::string("Bad user input: ") + user_input ) 并且用户输入包含格式攻击怎么办?您的程序将是敬酒!

标签: c++ string pointers constants


【解决方案1】:

试试这个

catch (exception e) 
{ 
         syslog (LOG_ERR, "exception: %s" ,e.what());   
}

【讨论】:

    【解决方案2】:

    使用带有const char*std::string 构造函数,参见reference。因此,您的日志记录代码可以更正如下:

    catch (const exception& e) {
        syslog (LOG_ERR, (std::string("exception: ") + e.what()).c_str());
    }
    

    【讨论】:

    • @Angel.King.47:显然 syslog 将 const char* 作为第二个参数,所以将调用添加到 c_str()
    【解决方案3】:

    如果你使用的是syslog(3),那么它被定义为:

    void syslog(int priority, const char *message, ...);
    

    您要使用syslog 的类似printf 的功能:

    catch (const std::exception& e) 
    { 
        syslog(LOG_ERR, "exception: %s", e.what());
    }
    

    或者您可以使用std::string::c_str 成员函数将std::string 转换为const char*

    catch (const std::exception& e)
    {
        std::string message = std::string("exception: ") + e.what();
        syslog(LOG_ERR, message.c_str());
    }
    

    另一个注意事项,通过 const-reference 捕获,否则实际抛出的异常对象很有可能获得 sliced

    【讨论】:

      猜你喜欢
      • 2010-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-22
      • 1970-01-01
      相关资源
      最近更新 更多