1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
|
// u2cp437.cpp
//
// Convert a UTF-8 Unicode text file to a Code Page 437 text file.
//
// Copyright (c) 2010 Michael Thomas Greer
// Distributed under the Boost Software License, Version 1.0.
// ( See file at http://www.boost.org/LICENSE_1_0.txt )
//
#include <iostream>
#include <string>
using namespace std;
#include <windows.h>
const char BOM[] = "\xEF\xBB\xBF";
//----------------------------------------------------------------------------
int main()
{
unsigned line_count = 0;
string s;
while (getline( cin, s ))
{
// Get rid of the stupid UTF-8 BOM
if (!line_count)
{
if (s.find( BOM ) == 0)
s.erase( 0, 3 );
}
line_count += 1;
// The following stuff fails for empty lines, so we'll handle that here
//
if (!s.length())
{
cout << endl;
continue;
}
// Convert UTF-8 to wchar_t[]
//
int count = MultiByteToWideChar(
65001, // CP_UTF8
0,
s.c_str(),
s.size(),
NULL,
0
);
if (!count)
{
switch (GetLastError())
{
case ERROR_INSUFFICIENT_BUFFER: cerr << "line " << line_count << ": insufficient buffer\n"; break;
case ERROR_INVALID_FLAGS: cerr << "line " << line_count << ": invalid flags\n"; break;
case ERROR_INVALID_PARAMETER: cerr << "line " << line_count << ": invalid parameter\n"; break;
case ERROR_NO_UNICODE_TRANSLATION: cerr << "line " << line_count << ": invalid unicode char\n"; break;
default: cerr << "line " << line_count << ": fooey\n";
}
}
wstring s_wide( count, '\0' );
MultiByteToWideChar(
65001, // CP_UTF8
0,
s.c_str(),
s.size(),
const_cast <wchar_t*> ( s_wide.c_str() ),
count
);
// Convert wchar_t[] to CP 437
//
string s_cp437( count, '\0' );
WideCharToMultiByte(
437,
0,
s_wide.c_str(),
count,
const_cast <char*> ( s_cp437.c_str() ),
count,
NULL,
NULL
);
// Display the converted line
//
cout << s_cp437 << endl;
}
// All done
return 0;
}
|