Recent

Author Topic: Problem with read  (Read 1133 times)

hiimic

  • Newbie
  • Posts: 1
Problem with read
« 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.
« Last Edit: March 31, 2020, 05:26:55 pm by hiimic »

MaxCuriosus

  • Full Member
  • ***
  • Posts: 136
Re: Problem with read
« Reply #1 on: March 31, 2020, 09:34:21 pm »
I would use ReadLn instead of Read, because an integer can have more than one digit.

lucamar

  • Hero Member
  • *****
  • Posts: 4219
Re: Problem with read
« Reply #2 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.
Turbo Pascal 3 CP/M - Amstrad PCW 8256 (512 KB !!!) :P
Lazarus/FPC 2.0.8/3.0.4 & 2.0.12/3.2.0 - 32/64 bits on:
(K|L|X)Ubuntu 12..18, Windows XP, 7, 10 and various DOSes.

 

TinyPortal © 2005-2018