字符串到Wstring C ++ Visual Studio

时间:2016-05-05 06:44:09

标签: c++ string visual-studio wstring

如何将String转换为WString。

在转换EscapeXML之前我需要首先将字符串转换为wstring。

示例:

我有一个字符串值=“&&&&”,然后我想将此字符串转换为wstring。

我的源代码:

string escapeXML(const std::string & value)
{
   // Here
   CA2W ca2w(value.c_str());
   wstring value = ca2w;

    int output_size = EscapeXML(value.c_str(), value.length(), 0, 0, ATL_ESC_FLAG_ATTR);

    std::wstring testout;
    testout.resize(output_size);
    EscapeXML(value.c_str(), value.length(), &testout[0], output_size, ATL_ESC_FLAG_ATTR);

    using convert_type = std::codecvt_utf8<wchar_t>;
    std::wstring_convert<convert_type, wchar_t> converter;

    string converted_str = converter.to_bytes(testout);

    return converted_str;
}

int main()
{

std::string test =  " & & & ";
cout << escapeXML(test) << '/n';

    return 0;
}

我的输出:

C2082: redefinition of formal parameter 'value'
IntelliSense: argument of type "const char *" is incompatible with parameter of type "const wchar_t *"

1 个答案:

答案 0 :(得分:0)

我现在发现了问题。问题在于重复价值。

我在字符串中调用了值,在wstring中调用了值。这种方式不应该起作用。我改变了估值,这是解决方案。感谢。

#include "stdafx.h"
#include "atlenc.h"
#include <string>
#include <iostream>
#include <codecvt>
using namespace std;


string escapeXML(const std::string & value)
{
    CA2W ca2w(value.c_str());
    wstring value2 = ca2w;
    int output_size = EscapeXML(value2.c_str(), value.length(), 0, 0, ATL_ESC_FLAG_ATTR);

    std::wstring testout;
    testout.resize(output_size);
    EscapeXML(value2.c_str(), value2.length(), &testout[0], output_size, ATL_ESC_FLAG_ATTR);

    using convert_type = std::codecvt_utf8<wchar_t>;
    std::wstring_convert<convert_type, wchar_t> converter;

    string converted_str = converter.to_bytes(testout);

    return converted_str;
}



int main()
{

    std::string test =  " Bayern & Münschen";
    std::string test2 = " \" \" \" ";
    std::string test3 = " ' ' ' ";
    std::string test4 = "< < <";
    std::string test5 = " > > >";

    cout << escapeXML(test);
    cout << escapeXML(test2) << '/n';
    cout << escapeXML(test3) << '/n';
    cout << escapeXML(test4) << '/n';
    cout << escapeXML(test5) << '/n';

    return 0;
}