Trying to print chess pieces in Visual Studio 2013 [duplicate] - c++

This question already has answers here:
Unicode character Visual C++
(2 answers)
Closed 8 years ago.
I am trying to print a "pawn" while using visual studio and it doesn't recognize the unicode.
can anyone tell me how to fix it?
this is a basic example:
#include <iostream>
using namespace std;
int main()
{
cout << "\33[37;42m\u2659\33[0m";
}
and the output i get is:
"<-[37;42m?<-[0m".

The ordinary Windows console windows do not support ANSI escape sequences.
To display general Unicode characters you can
use the Windows console functions instead, or
set up standard data streams to Unicode (Microsoft extension, see _setmode) and use wide streams, or
e.g. display a text file with the desired text, e.g. encoded in UCS-2.
Example 1: Using the Windows console functions.
Code:
#undef UNICODE
#define UNICODE
#include <windows.h>
#include <string>
namespace console {
using std::wstring;
const HANDLE output = GetStdHandle( STD_OUTPUT_HANDLE );
void write( const wstring& text )
{
if( text.length() == 0 ) { return; }
DWORD n_chars_written = 0;
WriteConsole( output, &text[0], text.length(), &n_chars_written, 0 );
}
}
auto main() -> int
{
console::write( L"Oh look, a \u2659!\n" );
}
Running this in the ordinary Windows console will most likely produce a square instead of a pawn symbol, even in Windows 8.x with e.g. Lucida Console font. That’s because the console window implementation simply does not support presentation of such characters. The character is correctly stored, and you can copy it out and e.g. present it in Windows Write (standard accessory program), but that’s a tad impractical, shall we say, for the ordinary end user.
A simple solution is to require use of e.g. the Console console window replacement.
Then you get nifty tabs, too. ;-)
H:\dev\test\so\0208>g++ using_console_api.cpp
H:\dev\test\so\0208>a
Oh look, a ♙!
H:\dev\test\so\0208>_
Example 2: using wide streams.
Code:
#include <assert.h>
#include <iostream>
#include <fcntl.h> // _O_WTEXT
#include <io.h> // _setmode, _isatty
namespace console {
struct Usage
{
Usage()
{
const int out_fileno = _fileno( stdout );
assert( _isatty( out_fileno ) );
_setmode( out_fileno, _O_WTEXT );
}
};
} // console
const console::Usage console_usage;
auto main() -> int
{
using namespace std;
wcout << L"Oh look, a \u2659!" << endl;
}
I recall that at one time, probably with the original MinGW g++, one had to define some special preprocessor symbol to get the Microsoft library extensions defined. However, this compiled nicely as-is with MinGW g++ 4.9.1 from the Nuwen distribution. And of course, it also compiles nicely with Visual C++.

Related

Unicode output not showing

I'm trying to learn Unicode programming in Windows.
I have this simple program:
#include <iostream>
#include <string>
int main()
{
std::wstring greekWord = L"Ελληνικά";
std::wcout << greekWord << std::endl;
return 0;
}
However, it outputs nothing. Any ideas how to make it output Greek?
I tried adding non-Greek letters, and that didn't work quite right either.
The first thing to try is to make the program not dependent on the encoding of the source file. So use Unicode escapes not literal Unicode letters
std::wstring greekWord = L"\u0395\u03BB\u03BB\u03B7\u03BD\u03B9\u03BA\u03AC";
Having the incorrect encoding in the source file is only one thing of many things that could be preventing you from printing Greek. The other obvious issue is the ability of your terminal to print Greek letters. If it can't do that, or needs to be set up correctly so that it can then nothing you do in your program is going to work.
And probably you want to fix the source code encoding issue, so that you can use unescaped literals in your code. But that's dependent on the compiler/IDE you are using.
If you are outputting your cout to a normal console then the console doesn't usually support unicode text like greek, try setting it up for unicode text or find another way to output your data, like txt files or some gui,
There are two way to do this.
The old, non-standard Microsoft way is as follows:
#include <fcntl.h>
#include <io.h>
int main()
{
_setmode(_fileno(stdout), _O_U16TEXT);
_setmode(_fileno(stdin), _O_WTEXT);
// your code here
}
You will fild this everywhere, but this is not necessarily a good way to solve this problem.
The more standards-compliant way is as follows:
#include <locale>
int main()
{
std::locale l(""); // or std::locale l("en_US.utf-8");
std::locale::global(l); // or std::wcout.imbue(l); std::wcin.imbue(l);
// your code here
}
This should work with other modern compilers and operating systems too.
TRY this it works with me :
#include
#include <io.h>
#include <fcntl.h>
using namespace std;
int main() {
_setmode(_fileno(stdout),_O_U16TEXT);
wcout<<L"Ελληνικά";
setlocale(LC_ALL,"");
return 0;
}

How to output low ASCII using C++ in Windows 10?

I'm trying to output directional arrows for a simple snake game in C++ on Windows 10. However, using this table as reference:
ASCII reference
All I got is this tiny question mark in the console:
Tiny question mark
I would like to output the symbols 16, 17, 30 and 31. I'm not much of programmer so it could be some basic mistake, but some symbols do work while others result in that symbol above.
A small example:
void showSnake() {
char snakeHead;
snakeHead = 31;
cout << snakeHead; //THIS SHOWS THE TINY QUESTION MARK
snakeHead = 62;
cout << snakeHead; //THIS SHOWS THE ">" SYMBOL
}
You should use Unicode, you'll have much more choices for characters.
On https://en.wikipedia.org/wiki/List_of_Unicode_characters I found this symbol '▶' which looks similar to what you wanted to use.
Its unicode value is U+25BA which means you can create a character with a value of '\u25BA' in C++.
In practice however that value would go outside the range of the char type so you have to use wide characters (wchar) to get the job done.
As per this answer you should also toggle support for Unicode character in stdout using the _setmode function (see here) from the C run-time library.
#include <iostream>
#include <io.h>
#include <fcntl.h>
int main() {
_setmode(_fileno(stdout), _O_U16TEXT);
std::wcout << L'\u25BA';
}

Is it possible to unify std::wstring behavior in VSVC and GCC?

Here a little code that reads a line from UFT-8 file:
#include <iostream>
#include <io.h>
#include <fcntl.h>
#include <locale>
#include <fstream>
#include <codecvt>
int main()
{
_setmode(_fileno(stdout), _O_U8TEXT);
auto inputFileStream = std::wifstream("input.txt");
const auto utf8Locale = std::locale(std::locale(), new std::codecvt_utf8<wchar_t>());
inputFileStream.imbue(utf8Locale);
std::wstring line;
std::getline(inputFileStream, line);
std::wcout << line << std::endl;
inputFileStream.close();
return 0;
}
When I build it with the Visual Studio Visual C++ compiler, I got the next result:
test τεστ тест
as expected.
By when I use MinGW with the GCC compiler, I got
琀攀猀琀 쐃딃쌃쐃 䈄㔄䄄䈄
As you understand, it's not the expected result.
Does any simple way exist to fix the output for GCC to the expected string?
OR
Does any simple way exist to use UTF-8 for both MSVC and GCC?
Answer (thanks for Igor Tandetnik and Remy Lebeau):
Seems, we must specify endian mode explicitly, because MSVC and GCC have different defaults. So
new std::codecvt_utf8<wchar_t, 0x10ffff, std::little_endian>()
should be used.
Fixed code:
#include <iostream>
#include <io.h>
#include <fcntl.h>
#include <locale>
#include <fstream>
#include <codecvt>
int main()
{
_setmode(_fileno(stdout), _O_U8TEXT);
auto inputFileStream = std::wifstream("input.txt");
const auto utf8Locale = std::locale(std::locale(), new std::codecvt_utf8<wchar_t, 0x10ffff, std::little_endian>());
inputFileStream.imbue(utf8Locale);
std::wstring line;
std::getline(inputFileStream, line);
std::wcout << line << std::endl;
inputFileStream.close();
return 0;
}
For your second question, one option is to limit the use of utf16 and std::w-prefixed stuff to the cases when you need to exchange utf16-encoded strings with the operating system. This happens when you receive arguments in wmain, open file with _wfopen, call Windows API function, etc. Otherwise, you would store, get from the user and return to the user utf8 strings using char type (char*, std::string, etc). Conversion between utf8 and utf16 can be done with MultiByteToWideChar and WideCharToMultiByte, bypassing the retarded c++ encoding api. The place where this does not work well is console input/output. Overall, you can output utf8 to the console if the user sets chcp 65001 and a ttf font. At least in Windows 7, you will also have to make sure not to split a character between two write calls, otherwise it will not print correctly (this also implies you cannot use std::cout, because msvcrt will call putc for every byte separately, and you'll need to use puts, fprintf, etc instead); I heard that this was fixed in Windows 10, but cannot confirm. Reading utf8 from the console with file api does not work as far as I know; if you want that, you'd need to detect that stdin is attached to a console and use console api instead.

How can I enumerate all the file in a directory in vfs c or c++? [duplicate]

This question already has answers here:
How do you get a directory listing in C?
(9 answers)
Recursive function for listing all files in sub directories
(10 answers)
Closed 10 years ago.
I need to enumerate all the file in a folder and then navigate to the subfolder and do the same (recursion? sure).
Ideally the algorithm should work in the same way on linux & macos
DISCLAIMER: I have asked a similar question on POSIX: I'm now aware of VFS but I'm puzzled to use VFS for enumerate dir. Any suggestion ? Should I open a dir as file ? The only way is to use a library cross platform like qt ?
UPDATE: so no VFS way to work on directory? "*V*irtual *F*ile *S*ystem provides a single API for accessing various different file systems" but no way to enumerate directory.
The "readdir" etc solution will do the trick on any type of *NIX ? And on windows nothing better than the huge MingW lib? or partial impletion working on only some win like:
https://github.com/xbmc/xbmc/blob/master/tools/TexturePacker/Win32/dirent.c
The BOOST seem to be a really cool solution but it's complex and academic. thnks in any case
LAST UPDATE:
I have found some more doc and now everything is a lot more clear.
This question is a duplicate!
opendir() and readdir() are the solution to enumerate and browse directory on linux. As shown on my example is quite easy to map them on windows (but the incoerent windowz fs make everything strange) and ntfw() is even more useful.
VFS (the virtual file switch) is a kernel feature that resolves this problem by creating an abstraction layer for file-system operations. closed doc here: linux programming interface
thnks!
You want to look at nftw. Here's an example that just recursively prints the contents of a directory in C (Untested):
#define _XOPEN_SOURCE 500
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <ftw.h>
int
print( const char *path, const struct stat *s, int flag, struct FTW *f )
{
puts( path );
return 0;
}
int
main( int argc, char **argv )
{
while( *++argv ) {
if( nftw( *argv, print, 1024, FTW_DEPTH )) {
perror( *argv );
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
Here is how I do it using Boost.Filesystem:
#include "boost/filesystem.hpp"
#include <iostream>
int main () {
for ( boost::filesystem::recursive_directory_iterator end, dir("./");
dir != end; ++dir ) {
// std::cout << *dir << "\n"; // full path
std::cout << dir->path().filename() << "\n"; // just last bit
}
}
Or, more succinctly:
#include "boost/filesystem.hpp"
#include <iostream>
#include <iterator>
#include <algorithm>
int main () {
std::copy(
boost::filesystem::recursive_directory_iterator("./"),
boost::filesystem::recursive_directory_iterator(),
std::ostream_iterator<boost::filesystem::directory_entry>(std::cout, "\n"));
}
Unix/Linux/Windows all have versions of readdir(). You can use it to get what the file system knows about files.

c++ string UTF-8 encoding [duplicate]

This question already has answers here:
How do I print UTF-8 from c++ console application on Windows
(8 answers)
Closed 9 years ago.
I'm new in c++, and I tried to write a very simple code, but the result is wrong, and I don't know how to fix it.
The code is:
#include <iostream>
#include <string>
using namespace std;
int main() {
string test_string = "aáeéöôőüűč♥♦♣♠";
cout << test_string << endl;
return 0;
}
But the result is: a├íe├ę├Â├┤┼Ĺ├╝┼▒─ŹÔÖąÔÖŽÔÖúÔÖá
I am on Windows, using Code::Blocks.
Save file as UTF-8 without BOM signature, and try use printf().
//Save As UTF8 without BOM signature
#include <stdio.h>
#include <windows.h>
int main() {
SetConsoleOutputCP(65001);
char test_string[] = "aáeéöôőüűč♥♦♣♠";
printf(test_string);
return 0;
}
And the result is: aáeéöôőüűč♥♦♣♠
Unfortunately working with UTF-8 on Windows is very problematic.
On Linux, you can simply wstring like this:
Does this code work universaly, or is it just my system?
But unfortunately Windows doesn't have an UTF-8 locale, so you are left with Windows API.
http://www.siao2.com/2007/01/03/1392379.aspx