Reputation: 43
I want to convert the special character for EscapeXML on Visual Studio C++.
#include "stdafx.h"
#include "atlenc.h";
#include <string>
#include <iostream>
using namespace std;
int main()
{
std::string test = "& & &";
inline int EscapeXML(const wchar_t * test)throw();
cout << test;
return 0;
}
I want to have an output.
& & &
Visual Studio has EscapeXML function, but it doesn't convert. https://msdn.microsoft.com/en-us/library/y0y57exc(v=vs.71).aspx
Upvotes: 0
Views: 442
Reputation: 26
There are several things wrong with your code. To begin with, you shouldn't end an #include directive with a semicolon.
That said, the main problem is that your code isn't calling EscapeXML, it's actually redefining it. What you want is something like this:
#include "stdafx.h"
#include "atlenc.h"
#include <string>
#include <iostream>
int main()
{
std::wstring test = L"& & &";
int output_size = EscapeXML(test.c_str(), test.length(), 0, 0, ATL_ESC_FLAG_ATTR);
std::wstring testout;
testout.resize(output_size);
EscapeXML(test.c_str(), test.length(), &testout[0], output_size, ATL_ESC_FLAG_ATTR);
std::wcout << testout;
return 0;
}
Note that EscapeXML expects a pointer to a wide string (wchar_t *), so you need to use std::wstring (and std:wcout). You need to pass it both the input string and a buffer into which it can write the "escaped" version.
Since we don't know ahead of time how big the buffer needs to be, we call EscapeXML with a null pointer - most Windows API functions that return strings let you do this, and they will return the required buffer size. We then instantiate another wstring, resize it to the required size, and call EscapeXML again, this time actually passing the pointer to the buffer. In fact, since c_str() returns a const pointer (which we can't pass to a function expecting a non-const pointer, unless we use const_cast), we instead pass a pointer to testout[0], which is the beginning of the wstring's internal string buffer.
Upvotes: 1