相关疑难解决方法(0)

如何将wstring转换为字符串?

问题是如何将wstring转换为字符串?

我有下一个例子:

#include <string>
#include <iostream>

int main()
{
    std::wstring ws = L"Hello";
    std::string s( ws.begin(), ws.end() );

  //std::cout <<"std::string =     "<<s<<std::endl;
    std::wcout<<"std::wstring =    "<<ws<<std::endl;
    std::cout <<"std::string =     "<<s<<std::endl;
}
Run Code Online (Sandbox Code Playgroud)

注释掉的输出是:

std::string =     Hello
std::wstring =    Hello
std::string =     Hello
Run Code Online (Sandbox Code Playgroud)

但不仅仅是:

std::wstring =    Hello
Run Code Online (Sandbox Code Playgroud)

这个例子有什么不对吗?我可以像上面那样进行转换吗?

编辑

新的例子(考虑到一些答案)是

#include <string>
#include <iostream>
#include <sstream>
#include <locale>

int main()
{
    setlocale(LC_CTYPE, "");

    const std::wstring ws = L"Hello";
    const std::string s( ws.begin(), ws.end() );

    std::cout<<"std::string =     "<<s<<std::endl;
    std::wcout<<"std::wstring =    "<<ws<<std::endl;

    std::stringstream ss;
    ss …
Run Code Online (Sandbox Code Playgroud)

c++ unicode stl wstring

191
推荐指数
13
解决办法
26万
查看次数

已弃用标头<codecvt>替换

一点前景:我的任务需要将UTF-8 XML文件转换为UTF-16(当然还有正确的标题).所以我搜索了将UTF-8转换为UTF-16的常用方法,并发现应该使用来自的模板<codecvt>.

但现在当它被弃用时,我想知道执行相同任务的新常用方法是什么?

(根本不介意使用Boost,但除此之外我更喜欢尽可能靠近标准库.)

c++ utf-8 utf-16 codecvt c++17

54
推荐指数
4
解决办法
1万
查看次数

C ++如何在给定位置将wstring插入向量

我想知道,是否有人可以向我解释 vector.insert() 方法中的第二个参数:

迭代器插入(迭代器位置,const value_type& val);

例如,我有一个 wstring 类型的向量,我想在给定位置插入一个 wstring。我已经弄清楚如何使用迭代器设置位置:

wstring word = "test";
int insertion_pos = 3;
iterator it = words.begin();
words.insert( it + insertion_pos, word );
Run Code Online (Sandbox Code Playgroud)

但是第二个论点呢?如何将 wstring 对象传递给 insert() 方法?非常感谢。

干杯,

马丁

完整示例:

#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <wchar.h>
#include <vector>

using namespace std;

int main(void) {
    // Initialize the vecor with three words.
    vector<wstring> words;
    wstring word1 = "FirstWord"; // Error msg: no viable conversion from 'const char     [10]' to 'wstring' (aka 
                             //            'basic_string<wchar_t>') …
Run Code Online (Sandbox Code Playgroud)

c++ vector wstring

3
推荐指数
1
解决办法
4195
查看次数

标签 统计

c++ ×3

wstring ×2

c++17 ×1

codecvt ×1

stl ×1

unicode ×1

utf-16 ×1

utf-8 ×1

vector ×1