Pascal - read/readln 函数杂质?

发布于 2024-11-02 01:47:31 字数 629 浏览 1 评论 0原文

我真的很感兴趣 - 为什么在从键盘读取一些值后需要将

readln;

行放入变量中?例如,

repeat
writeln('Make your choise');
read(CH);

if (CH = '1') then begin
writeln('1');
end;

{ ... }
until CH = 'q';

如果运行以下代码,并按键盘上的“1”,则会得到类似的输出。

1
Make your choise
Make your choise
Make your choise

另一方面,如果添加“readln;”行,一切都很完美:

repeat
writeln('Make your choise');
read(CH);
readln;

if (CH = '1') then begin
    Writeln('1');
end

until CH = 'q';

我唯一的猜测是,调用不带参数的 readln 会终止读取键盘输入的过程。但如果是这样,为什么 read/readln 函数不能停止读取输入以避免这种笨拙?

I'm really interested - why do you need to put

readln;

line after reading some value from keyboard into variable? For example,

repeat
writeln('Make your choise');
read(CH);

if (CH = '1') then begin
writeln('1');
end;

{ ... }
until CH = 'q';

If you run the following code, and press '1' on keyboard, you get an output like

1
Make your choise
Make your choise
Make your choise

On the other hand, if you add that "readln;" line, it all works perfect:

repeat
writeln('Make your choise');
read(CH);
readln;

if (CH = '1') then begin
    Writeln('1');
end

until CH = 'q';

My only guess is that calling readln without arguments terminates the process of reading the keyboard input. But if so, why cant the read/readln functions stop reading input themselves, to avoid such a clumsiness?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

纵山崖 2024-11-09 01:47:31

read 读取一个字符,但仍然期望在返回之前按下 Enter,即使它只返回 1 个字符。您在 1 之后按 Enter,控制台将用 CR (ASCII 0xd) 和 LF (ASCII 0xa) 填充键盘缓冲区。 (在 Linux/UNIX 系统上,Make your choise 只会出现两次,因为 UNIX 仅使用 LF 作为其换行符)。您可以通过打印 ord(CH) (iirc) 接收到的字符值来查看这些内容。

第二个程序使用后续的 readln 将 CRLF 组合从键盘缓冲区中拉出并丢弃它,因此它的行为方式与您似乎想要的一样。

如果这是一个一次性程序,只需通过 readln 执行即可,然后继续解决您正在处理的任何更重要的问题。如果它要用于生产,请通过围绕 readkey 的某种循环(在一个字符后立即返回)构建一个输入函数。

谢谢你的怀旧。

read reads a character, but still expects Enter to be pressed before returning, even though it only returns 1 character. You're pressing Enter after 1, and the console is stuffing the keyboard buffer with a CR (ASCII 0xd) and a LF (ASCII 0xa). (On a Linux/UNIX system, Make your choise will only appears twice, because UNIX uses only a LF as its linefeed character). You can see these by printing the values of the character received with ord(CH) (iirc).

The second program is pulling the CRLF combo out of the keyboard buffer with the subsequent readln and discarding it, so it behaves in the way you seem to want.

If this is a throwaway program, just do it via readln, and go on to solve whatever more important problem you're working on. If it's destined for production, build up an input function via a loop of some sort around readkey (which returns immediately after one character).

Thanks for the nostalgia.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文