C++ 将 std::wstring 转换为 int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23165199/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting a std::wstring to int
提问by user3434662
I presume this to be very simple but I cannot get it to work.
我认为这很简单,但我无法让它工作。
I am simply trying to convert a std::wstring to an int.
我只是想将 std::wstring 转换为 int。
I have tried two methods so far.
到目前为止,我已经尝试了两种方法。
The first is to use the "C" method with "atoi" like so:
第一种是将“C”方法与“atoi”一起使用,如下所示:
int ConvertedInteger = atoi(OrigWString.c_str());
However, VC++ 2013 tells me:
但是,VC++ 2013 告诉我:
Error, argument of type "const wchar_t *" is incompatable with parameter of type "const char_t *"
错误,“const wchar_t *”类型的参数与“const char_t *”类型的参数不兼容
So my second method was to use this, per Google search:
所以我的第二种方法是使用这个,每个谷歌搜索:
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.
}
However VC++ 2013 tells me this:
然而 VC++ 2013 告诉我这一点:
"Error: incomplete type not allowed."
“错误:不允许不完整的类型。”
What am I doing wrong here?
我在这里做错了什么?
Is there a better way to convert a std::wstring to int and back?
有没有更好的方法将 std::wstring 转换为 int 并返回?
Thank you for your time.
感谢您的时间。
回答by Thomas Petit
No need to revert to C api (atoi
), or non portable API (_wtoi
), or complex solution (wstringstream
) because there are already simple, standard APIs to do this kind of conversion : std::stoi
and std::to_wstring
.
无需恢复到 C api ( atoi
)、非可移植 API ( _wtoi
) 或复杂的解决方案 ( wstringstream
),因为已经有简单的标准 API 来进行这种转换:std::stoi
和std::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
回答by A B
you can use available API from wstring.h
.
您可以使用来自wstring.h
.
to convert WString
to int
try int ConvertedInteger = _wtoi(OrigWString);
.
转换WString
为int
try int ConvertedInteger = _wtoi(OrigWString);
。
for reference use msdn.microsoft.com/en-us/library/aa273408(v=vs.60).aspx.
参考使用 msdn.microsoft.com/en-us/library/aa273408(v=vs.60).aspx。