gpt4 book ai didi

delphi - XE7 ReadLn 命令中的 UTF8 文本问题

转载 作者:行者123 更新时间:2023-12-02 04:03:04 26 4
gpt4 key购买 nike

当我尝试在 Delphi XE7 控制台应用程序中显示 UTF 8 文本时,我遇到了一个愚蠢但烦人的情况。看来 ReadLn 命令在第二次尝试后才读取正确的 UTF 8 字符。例如:

    program ConsTest;

{$APPTYPE CONSOLE}

{$R *.res}

uses
System.SysUtils,
System.Classes,
WinApi.Windows;

var
CurrentCodePage: Integer;
Command: String;
Running: Boolean;
MyText: String;

begin
CurrentCodePage := GetConsoleOutputCP;
SetConsoleOutputCP(CP_UTF8);
SetTextCodePage(Output, CP_UTF8);

MyText := 'Olá mundo.';
WriteLn(MyText);

Running := True;
while Running do
begin
ReadLn(Command);
WriteLn(Command);
if (Command = '/q') then
Running := false;
end;

SetConsoleOutputCP(CurrentCodePage);
SetTextCodePage(Output, CurrentCodePage);
end.

在上面的示例中,在运行应用程序后,如果我输入以下文本:

“世界。”

WriteLn 将显示:

“世界。”

在第一遍之后,ReadLn 命令读取的所有 UTF-8 字符都显示正常。这段代码有问题吗?我尝试在网上搜索更多详细信息,但没有找到与此相关的任何信息。调用“WriteLn(MyText);”在代码的开头,显示文本“Olá mundo”。正确。

最佳答案

好的,在更加关注 Arioch 的第一条评论后,我尝试了下面的代码,它可以在任何控制台上完美运行。


program ConsTest;

{$APPTYPE CONSOLE}

{$R *.res}

uses
System.SysUtils,
System.Classes,
WinApi.Windows;

var
Command: String;
Running: Boolean;
MyText: String;

begin
MyText := 'Olá mundo.';
WriteLn(MyText);

Reset(Input); //*** That's the catch. ***

Running := True;
while Running do
begin
ReadLn(Input, Command);
if (MyText = Command) then
WriteLn('Yes')
else
WriteLn('No');

WriteLn(Command);
if (Command = '/q') then
Running := false;
end;
end.

*OBS:上面的代码不适用于某些字母,我需要更好地了解 Unicode 和 Delphi 中的控制台模式。由于某些巧合,它解决了我的问题,但不能被视为真正的答案。不管怎样,为了确保第一次调用 ReadLn 能够正常工作,对函数“Reset(Input)”的调用似乎是必要的。

关于delphi - XE7 ReadLn 命令中的 UTF8 文本问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30709116/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com