Lazarus

Free Pascal => Beginners => Topic started by: hiimic on March 31, 2020, 05:23:22 pm

Title: Problem with read
Post by: hiimic on March 31, 2020, 05:23:22 pm
Hi! I have a problem with read.
This is part of a program i wrote:

var b, c: char;
   a: integer;
begin
read(a);
read(b);
read(c);
writeln (a,b,c);

The problem is that, when i entry, for example, this values: 4 a c the program returns only 4 a.I think it's taking the blank space as a char, but when i write, for example, 4ac it returns an error. So i guess i'm not getting how to read correctly integers and char. What i dont det it either is tht i've seen a program using the same idea of reading and it works just fine, but when i do a similar one, i have to add a condition to not read blank spaces.
Title: Re: Problem with read
Post by: MaxCuriosus on March 31, 2020, 09:34:21 pm
I would use ReadLn instead of Read, because an integer can have more than one digit.
Title: Re: Problem with read
Post by: lucamar on March 31, 2020, 10:03:41 pm
I would use ReadLn instead of Read, because an integer can have more than one digit.

Read already "knows" how to read multi-digit numbers. The problem is reading the chars: since it's a valid char Read indeed  returns the space in c. To test this, try responding with "4 ac". It should give what you were expecting.

There is no easy way to solve this: you just have to keep reading and discarding the spaces or Read the integer and then ReadLn an string, strip out the spaces and move the characters to their varables.

This behaviour of Read() is why there are (and were) so many "low-level" functions to read specific type(s) from the console using KeyPressed / ReadKey.

Incidentally, note that Read can be used to read sevaral vars at once, so you could have  done: Read(a, b, c) with the same effect.
TinyPortal © 2005-2018