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

如何将std::wstring转换为unsigned long long?

问题:将std::wstring转换为unsigned long long时的编译错误

我需要将wstring转换为unsigned long long,尝试用以下代码实现:

ret.push_back(_wtol(s1));

编译器抛出错误:

No conversion available for "std::wstring" to const "wchar_t *"

完整代码如下:

vector<unsigned long long> splitW2(const wstring& uMain, const wstring& uSplitBy)
{
    vector<unsigned long long>ret;

    int iStart = 0;

    for (;;)
    {
        int iPos = uMain.find(uSplitBy, iStart);
        if (iPos == -1)
        {
            wstring s1;
            s1 = uMain.substr(iStart, uMain.size() - iStart);
            if (s1.size() > 0)
            {
                ret.push_back(_wtol(s1));//此处报错:无法将"std::wstring"转换为const "wchar_t *"
            }
            break;
        }
        else
        {
            wstring s2;
            s2 = uMain.substr(iStart, iPos - iStart);
            ret.push_back(s2);//这显然也不可行
            iStart = iPos + 1;
        }
    }
    return ret;
}

解决方法
  1. 修复参数类型不匹配问题
    _wtol函数要求传入const wchar_t*类型的参数,直接传std::wstring对象会报错,需要调用wstring的c_str()方法获取C风格字符串指针:
ret.push_back(_wtol(s1.c_str()));
  1. 使用匹配目标类型的转换函数
    _wtol返回long类型,和你需要的unsigned long long类型不匹配,若数值超出long范围会溢出。建议用专门转换为unsigned long long的_wstoull函数:
ret.push_back(_wstoull(s1.c_str(), nullptr, 10));

第三个参数10代表十进制基数,可根据需求调整为其他进制(如16表示十六进制)。

  1. 修正else分支的错误
    else分支里ret.push_back(s2)同样是类型不匹配,需要做相同转换,同时增加非空判断避免转换空字符串:
if (!s2.empty()) {
    ret.push_back(_wstoull(s2.c_str(), nullptr, 10));
}
  1. 修复find返回值的类型问题
    uMain.find()返回size_t(无符号整数),用int接收会有类型转换风险,判断找不到的条件应该用wstring::npos而非-1,修改后:
size_t iStart = 0;
// ...
size_t iPos = uMain.find(uSplitBy, iStart);
if (iPos == wstring::npos) {
    // ...
}
  1. 修正分隔符跳转逻辑
    原代码中iStart = iPos + 1仅跳过一个字符,若分隔符长度大于1会导致重复匹配,应改为跳过整个分隔符的长度:
iStart = iPos + uSplitBy.size();

修改后的完整代码:

#include <vector>
#include <string>
#include <cstdlib>

using namespace std;

vector<unsigned long long> splitW2(const wstring& uMain, const wstring& uSplitBy)
{
    vector<unsigned long long> ret;

    size_t iStart = 0;

    for (;;)
    {
        size_t iPos = uMain.find(uSplitBy, iStart);
        if (iPos == wstring::npos)
        {
            wstring s1 = uMain.substr(iStart);
            if (!s1.empty())
            {
                ret.push_back(_wstoull(s1.c_str(), nullptr, 10));
            }
            break;
        }
        else
        {
            wstring s2 = uMain.substr(iStart, iPos - iStart);
            if (!s2.empty())
            {
                ret.push_back(_wstoull(s2.c_str(), nullptr, 10));
            }
            iStart = iPos + uSplitBy.size();
        }
    }
    return ret;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 14:32:21