我的问题与这个旧问题有关:Format specifiers for uint8_t, uint16_t, ...?
简单回顾一下,原问题涉及如何使用scanf的uint8_t、uint16_t、uint32_t和uint64_t格式说明符。
该问题的答案如下:
sscanf (line, "Value of integer: %" SCNd32 "\n", &my_integer);
但是有没有人知道如何实现宽字符串的情况下完成这个操作呢?例如:
std::wstring line;
swscanf (line.c_str(), L"Value of integer: %" SCNd16 L"\n", &my_integer);
上述代码行给我带来了一个连接错误。我相信这是因为SCNd16并不适用于宽字符串?
目前我的解决方案是在原始答案中创建std::string,然后将其转换为宽字符串。
sscanf_s(line.c_str(), "%" SCNd16 "\n", &sixteenBitInteger)
// code here to check for EOF and EINVAL
//then I convert it
typedef std::codecvt_utf8<wchar_t> ConverterType;
std::wstring_convert<ConverterType, wchar_t> converter;
std::wstring convertedString = converter.from_bytes(line);
但这种方法比较丑陋,我相信一定有更优雅的方式进行转换吧?如果理解我的用途有所帮助,我正在使用uint16_t类型来存储Web服务器的端口号,但我想将其转换为宽字符串以便于显示。此外,我正在使用C++11,如果有所改变,我确实可以访问boost库,但我宁愿不使用它们。