在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)或自定义转换函数进行字符串转换。

 便宜VPS测评
便宜VPS测评










