2016-05-04 49 views
0

我想在Visual Studio C++中轉換EscapeXML的特殊字符。EscapeXML C++ Visual Studio

#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; 
} 

我想要一個輸出。

&amp; &amp; &amp; 

Visual Studio具有EscapeXML函數,但它不轉換。 https://msdn.microsoft.com/en-us/library/y0y57exc(v=vs.71).aspx

回答

1

您的代碼有幾個錯誤。首先,你不應該用分號結束#include指令。

這就是說,主要的問題是你的代碼不調用EscapeXML,它實際上是重新定義它。你需要的是這樣的:

#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; 
} 

注意,將escapeXml需要一個指向一個寬字符串(wchar_t的*),所以你需要使用std :: wstring的(和std:wcout)。您需要將它傳遞給輸入字符串和緩衝區,並將其寫入「轉義」版本。因爲我們事先並不知道緩衝區需要多大,所以我們使用空指針調用EscapeXML - 大多數返回字符串的Windows API函數可以讓您這樣做,並且它們將返回所需的緩衝區大小。然後我們實例化另一個wstring,將其大小調整爲所需的大小,然後再次調用EscapeXML,這次實際將指針傳遞給緩衝區。事實上,由於c_str()返回一個const指針(我們不能傳遞給一個函數,期望一個非const指針,除非我們使用const_cast),我們反而將一個指針傳遞給testout [0],這是開始wstring的內部字符串緩衝區。