【问题标题】:What is the format specifier of error_code?error_code 的格式说明符是什么?
【发布时间】:2018-03-23 14:02:37
【问题描述】:

我正在尝试使用 Microsoft 的 cpprestsdk。我遇到了一个错误,所以我想检查错误代码。但我无法弄清楚error_code 的格式说明符,我收到了这个警告:

警告:格式“%d”需要“int”类型的参数,但参数 3 有类型‘const std::error_code’ [-Wformat=] printf("HTTP 异常 :: %s\nCode :: %d\n", e.what(), e.error_code());

我应该如何打印错误代码?虽然%d 有效,但我想知道实际的说明符,这样我就不会收到任何警告。

PS:我在这里看到了一些:https://msdn.microsoft.com/en-us/library/75w45ekt(v=vs.120).aspx,但我认为它们对我没有任何帮助。

【问题讨论】:

  • std::error_code 是一个。当然你不能在旧的 C printf 函数中使用它。您使用printf 开头的原因是什么?
  • 没什么,我只是想知道有没有办法做到这一点。

标签: c++ format-specifiers cpprest-sdk


【解决方案1】:

std::error_code 是一个类,不能作为 printf 参数传递。但是您可以传递由error_code::value() 返回的int 值。

【讨论】:

  • 他们也可以使用cout << 代替printf 输出它
  • @NathanOliver 我知道我可以,但是和 namespace std 有冲突,所以我想到了 printf。
  • @NikhilWagh 不要使用using namespace std;。只需使用std::cout
【解决方案2】:

这是一种方法:

#include <system_error>
#include <cstdio>

void emit(std::error_code ec)
{
    std::printf("error number: %d : message : %s : category : %s", ec.value(), ec.message(), ec.category().name());
}

但我们不要使用 printf...

#include <system_error>
#include <iostream>

void emit(std::error_code ec)
{
    std::cout << "error number : " << ec.value()
              << " : message : " << ec.message() 
              << " : category : " << ec.category().name()
              << '\n';
}

【讨论】:

    猜你喜欢
    • 2013-06-22
    • 2013-06-22
    • 1970-01-01
    • 2010-11-03
    • 2012-01-05
    • 2012-01-31
    • 2014-01-01
    • 1970-01-01
    • 2020-04-13
    相关资源
    最近更新 更多