c++ wstring如何转换类型
导读:在C++中,要将wstring转换为其他类型,可以使用相应的转换函数。以下是一些常见的转换示例: 将wstring转换为string: #include <iostream> #include <locale>...
在C++中,要将wstring
转换为其他类型,可以使用相应的转换函数。以下是一些常见的转换示例:
- 将
wstring
转换为string
:
#include <
iostream>
#include <
locale>
#include <
codecvt>
int main() {
std::wstring wstr = L"Hello, World!";
std::string str;
// 使用wstring_convert进行转换
std::wstring_convert<
std::codecvt_utf8<
wchar_t>
>
converter;
str = converter.to_bytes(wstr);
std::cout <
<
"Converted string: " <
<
str <
<
std::endl;
return 0;
}
- 将
string
转换为wstring
:
#include <
iostream>
#include <
locale>
#include <
codecvt>
int main() {
std::string str = "Hello, World!";
std::wstring wstr;
// 使用wstring_convert进行转换
std::wstring_convert<
std::codecvt_utf8<
wchar_t>
>
converter;
wstr = converter.from_bytes(str);
std::wcout <
<
"Converted wstring: " <
<
wstr <
<
std::endl;
return 0;
}
- 将
wstring
转换为int
:
#include <
iostream>
#include <
string>
int main() {
std::wstring wstr = L"12345";
int num;
// 使用std::stoi进行转换
try {
num = std::stoi(wstr);
std::cout <
<
"Converted int: " <
<
num <
<
std::endl;
}
catch (const std::invalid_argument&
e) {
std::cerr <
<
"Invalid argument: " <
<
e.what() <
<
std::endl;
}
catch (const std::out_of_range&
e) {
std::cerr <
<
"Out of range: " <
<
e.what() <
<
std::endl;
}
return 0;
}
- 将
int
转换为wstring
:
#include <
iostream>
#include <
string>
int main() {
int num = 12345;
std::wstring wstr;
// 使用std::to_wstring进行转换
wstr = std::to_wstring(num);
std::wcout <
<
"Converted wstring: " <
<
wstr <
<
std::endl;
return 0;
}
请注意,std::wstring_convert
和std::codecvt_utf8
在C++17中已被弃用,建议使用第三方库(如ICU)或自定义转换函数进行字符串转换。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: c++ wstring如何转换类型
本文地址: https://pptw.com/jishu/708898.html