[fpc-pascal] How to write text to the console?

Reinier Olislagers reinierolislagers at gmail.com
Mon Jul 16 09:10:26 CEST 2012


Hope I got your attention with the subject ;)

After having had help on the list I managed to write UTF8 text to the
Windows Vista console using 2.6
However, my test program (see attachment) fails on trunk.

See
http://lazarus.freepascal.org/index.php/topic,17548
for discussion (initially about other problem)
Also had a look at
http://www.mail-archive.com/fpc-devel@lists.freepascal.org/msg26232.html

This works in FPC 2.7.1:
WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), at s[1],length(s),bw,nil);
... but seems to be Windows-only.

What am I missing and what is the easiest cross-platform way to
output/accept UTF8 text to/from the console?

Should I set the console codepage back to the one in use before the
program ran? Should I also mess with SetConsoleCP and/or SetTextCodePage?

Thanks,
Reinier
-------------- next part --------------
program uniconsole;
// Works on Windows Vista x64 with Lucida console font and x86 FPC 2.6.1
// prints garbled output on FPC trunk
{$mode objfpc}{$H+}
{$APPTYPE CONSOLE}

uses
  {$IFDEF UNIX}{$IFDEF UseCThreads}cthreads,{$ENDIF}cwstring,{$ENDIF}
  {$IFDEF WINDOWS}
  Windows, ctypes,
  {$ENDIF}
  Classes;

var
{$IFDEF WINDOWS}
CurrentOutputCP: cuint;
{$ENDIF}
UTF8TestString: String; //I can use UTF8String here as well, no difference

begin
{$IFDEF WINDOWS}
// see 
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms686036%28v=vs.85%29.aspx
CurrentOutputCP:=GetConsoleOutputCP;
SetConsoleOutputCP(CP_UTF8);
//Note: no use of input console: SetConsoleCP and GetConsoleCP?
//Probably the delphi way of saying {$codepage utf8}; doesn't have any effect
//SetTextCodePage(Out, CP_UTF8); //no effect
{$ENDIF}
// File encoded as UTF8 without BOM; speciyfing {$codepage utf8} on top doesn't help/change anything
// The next line should print rose, wodka (Cyrillic) and ouzo (Greek)
UTF8TestString:= 'rosé, водка and οÏ?ζο';
writeln ('UTF8 test: ' + UTF8TestString);
{$IFDEF WINDOWS}
// reset console
SetConsoleOutputCP(CurrentOutputCP);
{$ENDIF}
end. 


More information about the fpc-pascal mailing list