Pascal read 函数奇怪的行为

发布于 2024-12-28 22:44:33 字数 577 浏览 1 评论 0原文

假设我想从终端读取同一行的三个变量,并且我想使用 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 技术交流群。

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

发布评论

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

评论(2

很糊涂小朋友 2025-01-04 22:44:33

当您读取整数或浮点数时,它所做的第一件事就是跳过空格。然后,它读取数字类型的字符,并使文件指针指向下一个字符(第一个字符对于您正在读取的数字类型来说不能被视为有效)。

当您读取字符时不会跳过空格,因为空格被视为有效字符。

如果你想跳过字符的空白,你需要自己做,比如:(

read (a, b, c);
while c = ' ' do begin
    read (c);
end

未经测试,并且大大扩展了我的记忆 - 我已经几十年没有在愤怒中做过 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:

read (a, b, c);
while c = ' ' do begin
    read (c);
end

(untested, and stretching my memory considerably - I haven't done Pascal in anger for decades).

〗斷ホ乔殘χμё〖 2025-01-04 22:44:33

如果您简单地将所有内容作为一个字符串抓取,然后用代码解析它,那么效果会更好。至少可以检查输入,防止任何类型不匹配错误。直接读取变量只会导致错误数据的运行时错误。

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.

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