Search code examples
delphidelphi-7

New to coding in Delphi 7: Unable to read() multiple strings


I have recently started coding in Delphi 7, mainly for school but also for personal entertainment. I have run into a problem I cannot solve. I wanted to make a console application, that asks you to input a couple of strings, such as your name and similar, so that the application may call you by your name later. However, I soon realized that having two "read();" commands for 2 different strings doesn't work for some reason, skipping the read command for the second string every time. Since I can't explain it perfectly, here is the simplest code I could think of that shows the problem:

program stringproblem;

{$APPTYPE CONSOLE}

uses
  SysUtils;

  var string1,string2:string;

begin
read(string1);
read(string2);
writeln(string1,string2);
readln;
readln;
end.

So the console opens, I get to write the value of string1, I input 'test', for example, but instead of letting me then input the value of string2, it skips that one, and just writes out 'test' in the console.

Why can't I input the values of two strings in an application? Why does writing the value of the first one automatically skip all others?


Solution

  • Instead of Read(string1) you should use Readln(string1). And likewise for the other read, and indeed whenever you wish to consume an entire line.

    From the documentation for Read:

    Read reads all characters up to, but not including, the next end-of-line marker or until Eof(F) becomes true; it does not skip to the next line after reading.

    After the first Read, each subsequent Read sees the end-of-line marker and returns a zero-length string.

    Use multiple Readln calls to read successive string values.