Reputation: 787
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
Upvotes: 3
Views: 2233
Reputation: 21
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.
Upvotes: 1
Reputation: 881393
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).
Upvotes: 6