Pascal read 函数奇怪的行为
假设我想从终端读取同一行的三个变量,并且我想使用 read 函数。我会使用示例输入编写类似下一个代码的内容:
10 929.1 x
var a:integer;
var b:real;
var c:char;
begin
read(a,b,c);
writeln (a, ' ', b, ' ' ,c);
end.
我永远不会读取字符“c”。我必须这样修复它:
var a:integer;
var b:real;
var c:char;
var d:char;
begin
read(a,b,d,c);
writeln (a, ' ', b, ' ' ,c);
end.
现在, char d 将读取空格,而 char c 将具有正确的值。
另外,如果我只想读取三个字符,则输入必须是“zyx”,否则我将不得不使用另一个读取来解决“xy z”的问题。
它与数字配合得非常好。它将读取“10 9 2”,而不需要额外的读取。
有人知道这背后的原因吗? (我已经用fpc和gpc尝试过了)
谢谢
Suppose I want to read three variables on the same line from the terminal and I want to use the read function. I would write something like the next code with the example input:
10 929.1 x
var a:integer;
var b:real;
var c:char;
begin
read(a,b,c);
writeln (a, ' ', b, ' ' ,c);
end.
I would never read the char "c". I would have to fix it like this:
var a:integer;
var b:real;
var c:char;
var d:char;
begin
read(a,b,d,c);
writeln (a, ' ', b, ' ' ,c);
end.
Now, the char d will read the blank space and the char c will have the correct value.
Also, If I only want to read three chars, the input would have to be "zyx" or I would have to use another reads to fix the problem for "x y z".
It works perfectly fine with numbers. It would read "10 9 2" without the need of extra reads.
Does anybody know the reason behind this? (I have tried it with fpc and gpc)
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您读取整数或浮点数时,它所做的第一件事就是跳过空格。然后,它读取数字类型的字符,并使文件指针指向下一个字符(第一个字符对于您正在读取的数字类型来说不能被视为有效)。
当您读取字符时不会跳过空格,因为空格被视为有效字符。
如果你想跳过字符的空白,你需要自己做,比如:(
未经测试,并且大大扩展了我的记忆 - 我已经几十年没有在愤怒中做过 Pascal 了)。
When you read an integer or a float, the first thing it does is to skip white space. Then it reads characters in for the numeric type and leaves the file pointer pointing to the next character (the first one that can't be considered valid for the numeric type you're reading in).
The skipping of white space doesn't happen when you read a character since white space is considered a valid character.
If you want to skip white space for characters, you need to do it yourself, with something like:
(untested, and stretching my memory considerably - I haven't done Pascal in anger for decades).
如果您简单地将所有内容作为一个字符串抓取,然后用代码解析它,那么效果会更好。至少可以检查输入,防止任何类型不匹配错误。直接读取变量只会导致错误数据的运行时错误。
You'd be FAR better off simply grabbing the whole lot as one string, then parsing it in code. At least then the input can be checked any type-mismatch errors can be prevented. Read()-ing directly into the variables will just cause run-time errors on bad data.