Yusufmm Yusufmm - 1 year ago 189
Pascal Question

How to get input of multiple char and longint separated by a space in single read()?

I tried this but it give me Runtime error 106.

a, c: char;
b, d: longint;
read(a, b, c, d);
write(a, ' ', b, ' ', c, ' ', d);

The input is

A 1 B 2

Answer Source

As @DavidHeffernan commented, and as @lurker explained, your code won't work as-is.

Assuming you have a FreePascal version that knows the TStringList type in unit Classes (I guess all recent ones do), you can do the following:

  Classes, SysUtils;

procedure Test;
  a, c: Char;
  b, d: Longint;
  s: string;
  sl: TStringList;
  sl := TStringList.Create;
    Writeln('Enter a char, a number, a char and a number again, separated by spaces:');
    // Read entire line

    // Split s into four entries in the string list
    sl.Delimiter := ' ';
    sl.DelimitedText := s;
    if sl.Count >= 4 then
      a := sl[0][1];         // first string item, convert to char
      b := StrToInt(sl[1]);  // second string item, convert to integer
      c := sl[2][1];         // third string item, convert to char
      d := StrToInt(sl[3]);  // fourth string item, convert to integer
  Writeln(a, ' ', b, ' ', c, ' ', d);


You should probably add error checking for the case you get bad input, and perhaps use TryStrToInt instead of StrToInt, but I'll leave that as an exercise.

As @lurker said, in your question, you are trying to read Chars, which causes problems, because for instance a space and a tab are also a Chars, so the space delimiters don't work as you expected here. This will mess up the entire input. The only way to get these items is to read the entire string and then to parse it (split it).

If your version of FreePascal has a unit StrUtils with a SplitString function in it, you can use that instead of a TStringList. It splits the string, using a given delimiter (here ' ') into a dynamic array. That is perhaps a little simpler, but not much.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download