You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何不转换为字符串即可获取wstringstream输出的各变量的长度

可行实现方案

方案1:利用流写入位置差值计算

该方案利用std::wstringstream内置的tellp()方法获取输出指针的位置偏移,两次取值的差值就是中间写入内容的宽字符长度,完全不需要手动将变量转字符串调用length(),适配所有流支持的输出类型。

#include <iostream>
#include <sstream>
#include <string>
#include <windows.h>

int main()
{
    int x              =  1000;
    std::wstring A     =  L"Hello World";
    HWND hwnd          =  (HWND)0x000103FC; // 修正原代码类型赋值错误,HWND为指针类型
    
    std::wstringstream ss;
    std::streampos pre_pos;

    // 统计x的输出长度
    ss << L"x: ";
    pre_pos = ss.tellp();
    ss << x;
    std::streamsize x_len = ss.tellp() - pre_pos;
    std::wcout << L"x: " << x_len << std::endl; // 输出4

    // 统计wstring的输出长度
    ss << L", wstring: ";
    pre_pos = ss.tellp();
    ss << A;
    std::streamsize str_len = ss.tellp() - pre_pos;
    std::wcout << L"wstring: " << str_len << std::endl; // 输出11

    // 统计hwnd的输出长度
    ss << L", hwnd: ";
    pre_pos = ss.tellp();
    ss << hwnd;
    std::streamsize hwnd_len = ss.tellp() - pre_pos;
    std::wcout << L"hwnd: " << hwnd_len << std::endl; // 输出10
       
    return 0;
}

该方案会自动适配你给流设置的格式化规则(比如十六进制输出、固定宽度、填充字符等),统计的是最终实际写入流的字符长度,比手动转字符串更准确。


方案2:封装通用统计工具(适合高频统计场景)

如果需要多次统计不同变量的输出长度,可以封装通用模板函数减少重复代码:

// 通用统计函数:写入变量同时返回写入长度
template<typename T>
std::streamsize write_and_count(std::wstringstream& ss, const T& value)
{
    auto pre = ss.tellp();
    ss << value;
    return ss.tellp() - pre;
}

// 调用示例
int main()
{
    int x              =  1000;
    std::wstring A     =  L"Hello World";
    HWND hwnd          =  (HWND)0x000103FC;
    
    std::wstringstream ss;
    ss << L"x: ";
    auto x_len = write_and_count(ss, x);
    ss << L", wstring: ";
    auto str_len = write_and_count(ss, A);
    ss << L", hwnd: ";
    auto hwnd_len = write_and_count(ss, hwnd);

    return 0;
}

内容的提问来源于stack exchange,提问作者user16852409

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 10:06:02