Pascal - read/readln 函数杂质?
我真的很感兴趣 - 为什么在从键盘读取一些值后需要将
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
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 aCR
(ASCII 0xd) and aLF
(ASCII 0xa). (On a Linux/UNIX system,Make your choise
will only appears twice, because UNIX uses only aLF
as its linefeed character). You can see these by printing the values of the character received withord(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 aroundreadkey
(which returns immediately after one character).Thanks for the nostalgia.