gpt4 book ai didi

c++ - 将 std::wstring 转换为 int

转载 作者:IT老高 更新时间:2023-10-28 22:33:08 30 4
gpt4 key购买 nike

我认为这很简单,但我无法让它工作。

我只是想将 std::wstring 转换为 int。

到目前为止,我已经尝试了两种方法。

第一种是使用带有“atoi”的“C”方法,如下所示:

int ConvertedInteger = atoi(OrigWString.c_str());

但是,VC++ 2013 告诉我:

错误,“const wchar_t *”类型的参数与“const char_t *”类型的参数不兼容

所以我的第二种方法是使用这个,根据谷歌搜索:

std::wistringstream win(L"10");
int ConvertedInteger;
if (win >> ConvertedInteger && win.eof())
{
// The eof ensures all stream was processed and
// prevents acccepting "10abc" as valid ints.
}

但是 VC++ 2013 告诉我:

“错误:不允许的类型不完整。”

我在这里做错了什么?

有没有更好的方法将 std::wstring 转换为 int 并返回?

感谢您的宝贵时间。

最佳答案

无需恢复为 C api (atoi),或非可移植 API (_wtoi),或复杂解决方案 (wstringstream),因为已经有简单的标准 API 来进行这种转换:std::stoistd::to_wstring

#include <string>

std::wstring ws = L"456";
int i = std::stoi(ws); // convert to int
std::wstring ws2 = std::to_wstring(i); // and back to wstring

关于c++ - 将 std::wstring 转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23165199/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com