Search code examples
inputpascallazarusfreepascal

Pascal - Input a various number of variables on 1 line


So I was thinking how is it possible to ask for an input of an unknown number of variables on one line only by using a space to separate them... For instance, if the number of variables I want to input is known, the code would be..

Readln(a,b,c)

This would ask for an input of 3 variables, split by a space or by pressing enter after each, but the split by using space is what I am going for. But what if I dont know the number of variables and I need to create them on the go?.. Say, n sets the number of variables I need to input.

readln(n);
( n = 2 )
readln(a,b..... any number of variables equal to n)

Note that the number of variables I read after n need to be equal to the number that n holds, and can not be pre-set in var. I tried different ways of doing this but all I came up with was

readln(n)
for i := 0 to n-1 do
  readln(a[i])

But by using the loop and array, I still can only input one variable on each line, not any number separated by a space. Is there any way to do this?


Solution

  • You should consider the string with the values a value itself. So you read once, into one variable. Then you process the result, i.e. splitting on spaces and handling any errors.

    For example:

    var
      ValuesSeparatedBySpaces: string;
      ValueList: TStringList;
      I: Integer;
    begin
      // Read all values together
      ReadLn(ValuesSeperatedBySpaces);
      // Create a list to split them into
      ValueList := TStringList.Create;
      try
        // Use the space character and only the space character for splitting
        ValueList.Delimiter := ' ';
        ValueList.StrictDelimiter := True;
        // Do the splitting
        ValueList.DelimitedText := ValuesSeparatedBySpaces;
        // Show the result
        for I := 0 to ValueList.Count - 1 do
          Writeln(ValueList[I]);
      finally
        // Clean up
        LValueList.Free;
      end;
    

    If you need to values of a different type (e.g. Integers) you need to do the conversion (e.g. StrToInt) after building the list of values.