pascal illegal qualifier error when calling function from a procedure - arrays

function classes(o:integer): String;
var allclasses : array[1..7] of String;
begin
allclasses[1]:= 'class1';
allclasses[2]:= 'class2';
allclasses[3]:= 'class3';
allclasses[4]:= 'class4';
allclasses[5]:= 'class5';
allclasses[6]:= 'class6';
allclasses[7]:= 'class7';
classes := allclasses[o];
end;
Above you can see a function, which should receive an integer and give a result of string that was stored in array.
procedure loadthis(chosen : string);
var f: text;
i : integer;
begin
Assign(f, 'files\'+chosen+'.txt');
Reset(f);
ReadLn(f, i);
MyChar.clas := classes[i];
end;
When this procedure is called, it calls a "classes" function. Pleae note that Mychar ir a global variable.
begin
loadthis(FileName);
ReadLn;
Readln
end.
Ant this is the main program, which calls "loadthis" procedure.
I Have no idea whats wrong, but I am getting these errors:
Wrong amount of parameters specified
Illegal qualifier
Both errors come from this line:
MyChar.clas := classes[i];. I have really no idea what is wrong, maybe I can not call a function from a procedure ? Please help.

You're trying to access it as an array index, but it needs to be a function call:
MyChar.clas := classes(i); { note () instead of [] }
You should probably add some range checking, too. What happens if someone puts 20 in the text file? Your array only has items at indexes 1 through 7, so you'll get a runtime error when you call classes(20) with the out of range value.
(You could probably use a constant array for allclasses to lessen your code as well, but your instructor probably haven't gotten that far yet.)
Given your comment about not having an instructor, here's a suggestion about a better way to handle the function:
function classes(o:integer): String;
const
allclasses: array[1..7] of string = ('class1',
'class2',
'class3',
'class4',
'class5',
'class6',
'class7');
begin
{
Low() returns the lowest index of the array, and
High() returns the highest. The if statement makes sure
that o is between them. It is the range check I mentioned.
}
if (o >= Low(allclasses)) and (o <= High(allclasses)) then
classes := allclasses[o]
else
classes := '';
end;

Related

TStringList in an array in Lazarus

I have a problem with TStringLists in Lazarus. I have an array called 'trans' of records called 'TTrans' which contain, among other things, TStringList called 'meebetalers'. So when I need to know for example the amount of lines in that StringList I would have to write this right?
trans[i].meebetalers.Count;
Anyways, I first create a stringlist and put the selected strings from a checklistbox in it, and that works (i.e. the program returns 3 when I ask for the Count, which is correct).
In this piece of code I add values to the StringList:
slmeebetalers := TStringList.Create;
for i:= 0 to Form6.CLBox.Count-1 do begin
if Form6.CLBox.Checked[i] then begin
slmeebetalers.Add(Form6.CLBox.Items[i]);
end;
end;
Then I put the stringlist a procedure, and in that procedure I assign my first created StringList to the stringlist I mentionned before (trans[i].meebetalers), see my piece of code next.
Unit6.VoegTransToe(Form6.TransNaam.Text,
Form6.TrComboBox.Text,
bedrag,
slmeebetalers,
Form6.CalendarDialog1.Date);
But when I then ask for the count, it returns 0.
procedure VoegTransToe(naam, betaalpers: string; bedrag: currency;
meebetalers: TStringList; datum: TDateTime);
begin
aantaltrans:= aantaltrans+1;
trans[aantaltrans].naam:=naam;
trans[aantaltrans].pers.naam:=betaalpers;
trans[aantaltrans].bedrag:=bedrag;
trans[aantaltrans].datum:=datum;
meebetalers:= TStringList.Create;
trans[aantaltrans].meebetalers:= TStringList.Create;
trans[aantaltrans].meebetalers.Assign(meebetalers);
meebetalers.Free;
//trans[aantaltrans].meebetalers.Free;
end;
note The difference in name of the variable is because they are in different units
With this code I don't get an error, but it returns 0. When I say //meebetalers.Free; the same happens.
But when I add //trans[aantaltrans].meebetalers.Free; I don't get an error while compiling, but when I call the procedure. Then I get this error:
Project project1 raised exception class 'External: SIGSEGV'.
I think there is something wrong with the Create and Free function, but I don't know what. When I implement the try...finally...end it returns the same error. Can anybody help me?
The problem is that your VoegTransToe() procedure is ignoring the populated TStringList object that is passed in via its meebetalers parameter. You are resetting meebetalers to point at a newly created empty TStringList object just before assigning meebetalers to trans[aantaltrans].meebetalers.
procedure VoegTransToe(naam, betaalpers: string; bedrag: currency;
meebetalers: TStringList; datum: TDateTime);
begin
aantaltrans:= aantaltrans+1;
trans[aantaltrans].naam:=naam;
trans[aantaltrans].pers.naam:=betaalpers;
trans[aantaltrans].bedrag:=bedrag;
trans[aantaltrans].datum:=datum;
// meebetalers:= TStringList.Create; // <-- GET RID OF THIS!
trans[aantaltrans].meebetalers:= TStringList.Create;
trans[aantaltrans].meebetalers.Assign(meebetalers);
//meebetalers.Free; // <-- AND THIS!
end;
Don't forget to Free() the input TStringList object when you are done using it:
slmeebetalers := TStringList.Create;
try
for i := 0 to Form6.CLBox.Count-1 do begin
if Form6.CLBox.Checked[i] then begin
slmeebetalers.Add(Form6.CLBox.Items[i]);
end;
end;
Unit6.VoegTransToe(..., slmeebetalers, ...);
finally
slmeebetalers.Free;
end;

How to output an array that has nested arrays in Pascal

I'm creating a basic concept of a music player using Pascal, but I'm struggling to display the albums inside it. The error I got says "(134, 29) Error: Can't read or write variables of this type". I'm assuming it's saying that because I'm using an array within an array, and it's having a hard time displaying both at the same time (although I only want it to display the albums, not the tracks as well).
Here's what my code looks like:
function ReadAllTrack(prompt: String): Tracks;
var
i: Integer;
trackArray: Array of Track;
trackCount: Integer;
begin
WriteLn(prompt);
trackCount := ReadIntegerGreaterThan1('Please enter the number of tracks you would like to add: ');
Setlength(trackArray, trackCount);
for i := 0 to trackCount - 1 do
begin
WriteLn('Enter the details for your track:');
trackArray[i] := ReadTrack();
end;
result := trackArray;
end;
function ReadAlbum(): Album;
begin
result.albumName := ReadString('Album name: ');
result.artistName := ReadString('Artist name: ');
result.albumGenre := ReadGenre('Genre:');
result.trackCollection := ReadAllTrack('Track Collection:');
end;
function ReadAllAlbums(): Albums;
var
i: Integer;
albumArray: Array of Album;
albumCount: Integer;
begin
albumCount := ReadIntegerGreaterThan1('Please enter the number of albums you would like to add: ');
Setlength(albumArray, albumCount);
for i := 0 to albumCount - 1 do
begin
WriteLn('Enter the details for your album:');
albumArray[i] := ReadAlbum();
end;
result := albumArray;
end;
procedure DisplayAlbumOptions(listOfAllAlbums: Albums);
var
userInput: Integer;
begin
WriteLn('1. Display all albums');
WriteLn('2. Display all albums for a genre');
userInput := ReadIntegerRange('Please enter a number (1, 2) to select: ', 1, 2);
case userInput of
1: WriteLn(listOfAllAlbums); //Error: Can't read or write variables of this type
end;
end;
Basically what this does is it will ask the user showing 5 options:
1. Add albums
2. Display albums
etc
If the user selects 1, the program will ask the user to input the number of albums they want to input. Then for each album it'll ask them to enter the details, and then the tracks.
Then if the user selects 2, the program will ask the user to choose either display every single album there is, or display all albums for a single genre (I'll be working on this one after solving this problem). At first I thought it would be just as simple as WriteLn(TheAlbumArray); but turns out it was more complicated than I thought because I don't think it's possible for the program to display it this way. I tried separating the albums and tracks so that it would only display the albums when I use WriteLn(TheAlbumArray); but it wasn't possible because the tracks still have to be "inside" the album so that when I display the albums and select one of them, it would then display the tracks....
Any help or suggestion for this and/or the second will be much appreciated ^^
Your original question contained a lot of superfluous detail. After the edit, you removed the type declarations, but kept much of the superfluous detail.
However, it is possible to discern the problem you are passing an array of record to Writeln. The Writeln function can accept only certain simple types as arguments, e.g. strings, numerical types, boolean. You certainly cannot pass an array to Writeln. You must iterate over the array and process each member individually.
So you might try
for i := low(listOfAllAlbums) to high(listOfAllAlbums) do
WriteLn(listOfAllAlbums[i]);
But that does not work either, because listOfAllAlbums[i] is a record, and a record is a compound type which cannot be passed to Writeln. So you need to process the record separately. If you want to display just the title, then you write:
for i := low(listOfAllAlbums) to high(listOfAllAlbums) do
WriteLn(listOfAllAlbums[i].albumName);
If you want to print the track titles too then you need to iterate over the array contained in the record.
for i := low(listOfAllAlbums) to high(listOfAllAlbums) do
begin
WriteLn(listOfAllAlbums[i].albumName);
for j := low(trackCollection) to high(trackCollection) do
WriteLn(listOfAllAlbums[i].trackCollection[j]);
end;
It is impossible to use composite types (arrays, records, ...) in Read[ln] and Write[ln] procedures.
To make your code more transparent you could to create type helper for your array(s) and use well-known AsString property. Here is example for simple array of Integer:
program foo;
{$mode objfpc}{$H+}
{$modeswitch typehelpers}
uses
Classes, SysUtils;
type
TMyArray = array of Integer;
TMyArrayHelper = type helper for TMyArray
private
function GetAsString: string;
procedure SetAsString(const AValue: string);
public
property AsString: string read GetAsString write SetAsString;
end;
function TMyArrayHelper.GetAsString: string;
var
i: Integer;
begin
Result := '';
for i in Self do
begin
if Result <> '' then
Result := Result + ', ';
Result := Result + IntToStr(i);
end;
Result := '[' + Result + ']';
end;
// Relatively simple parser
// Fill free to implement ones for your array type
procedure TMyArrayHelper.SetAsString(const AValue: string);
var
tmp, s: string;
items: TStringArray;
i: Integer;
begin
tmp := Trim(AValue);
if not (tmp.StartsWith('[') and tmp.EndsWith(']')) then
raise Exception.CreateFmt('Invalid array literal format: "%s"', [tmp]);
tmp := tmp.Trim(['[', ']']);
items := tmp.Split([',']);
for s in items do
try
StrToInt(s);
except
on e: Exception do
raise Exception.CreateFmt('Invalid integer literal: "%s"', [s]);
end;
SetLength(Self, Length(items));
for i := 0 to Length(items) - 1 do
Self[i] := StrToInt(items[i]);
end;
var
a1, a2: TMyArray;
begin
a1.AsString := '[1,2,3,5]';
Writeln('a1 = ', a1.AsString);
a2.AsString := a1.AsString;
a2[1] := 999;
Writeln('a2 = ', a2.AsString);
end.
Helper types in FreePascal
TStringHelper in SysUtils unit

How do i call a function within a function?

i'm creating a mini program in pascal to read music albums. The problem i'm facing is calling the readTracks() function within my readAlbum() function. Any help would be great, thank you :)
The current error when executing the code is:
Error: Incompatible types: got "albumRecord" expected "albumRecord.Dynamic Array Of trackRecord
type
trackRecord = record
trackName:string;
fileLocation: string;
end;
albumRecord = record
albumName:string;
tracks: array of trackRecord;
end;
function readTracks():albumRecord;
var
i:Integer;
numOfTracks:Integer;
begin
numOfTracks := readInteger('Enter number of tracks: ');
setLength(result.tracks, numOfTracks);
for i:= 0 to high(result.tracks)do
begin
Writeln('Enter Track ',i+1,' Details: ');
result.tracks[i].trackName := readString('Enter track name: ');
result.tracks[i].fileLocation := readString('Enter file
location: ');
end;
end;
function readAlbum (prompt: string): albumRecord;
begin
result.albumName := readString('Enter Album Name: ');
result.tracks := readTracks();
end;
I think you have managed to confuse yourself by the way you have declared your albumRecord.Tracks. What you should have done is to declare a trackArray type and declared your readTracks to return an instance of this array type.
Your main problem was that your readAlbum returns an albumRecord, but you had set up its tracks field to be assigned from readTracks, which returns the wrong type, i.e. albumRecord, rather than an array of tracks.
Put another way, as you have declared readAlbum to return an albumRecord, the compiler will generate code which, on entry to the function, sets up an instance of albumRecord on the stack, which is eventually returned as the return value of the function when it completes. Your code in the function is simply to fill out the fields of this record, not create another instance of it as your result.tracks := readTracks() would have done, given how you had declared readTracks.
The code below changes the declarations and code inside readTracks so that it does what you intend.
uses TerminalUserInput;
type
trackRecord = record
trackName:string;
fileLocation: string;
end;
trackArray = array of trackRecord;
albumRecord = record
albumName:string;
tracks: trackArray;
end;
function readTracks():trackArray;
var
i:Integer;
numOfTracks:Integer;
begin
numOfTracks := readInteger('Enter number of tracks: ');
setLength(result, numOfTracks);
for i:= 0 to high(result)do
begin
Writeln('Enter Track ',i+1,' Details: ');
result[i].trackName := readString('Enter track name: ');
result[i].fileLocation := readString('Enter file location: ');
end;
end;
function readAlbum (prompt: string): albumRecord;
begin
result.albumName := readString('Enter Album Name: ');
result.tracks := readTracks();
end;
begin
readAlbum('New album');
end.
Btw, I think you would find your code much clearer, when you come back to it after a while if you got into the habit of using a naming convention for declarations of record- and array types which distinguishes them from instances of them. One convention is to precede the type-name with a 'T', so your would be TtrackRecord, TalbumRecord, TtrackArray.
Also btw, in your q you say
The current error when executing the code is: Error: Incompatible types
Actually, that is not quite correct. The error occurs while the compiler is compiling the code, not when your code is executing. This is an important difference: your error is known as a compile-time error, whereas one which occurs when your program is executing (which it can only do once it has been successfully compiled) is known as a run-time error.
tracks is an array, and thus needs indexing. Which number are you reading?
In the for loop you do know how to index the array, so why can't you do it in readalbum?

Adding Values to an Array in Pascal - iIllegal Qualifier"

I am trying to create a program that prints 11 buttons so I wanted to use an array. The only change with these buttons is the name.
When I try to compile, I get the error "illegal qualifier" at my first array assignment.
type
buttonName = array[0..11] of String;
procedure PopulateButton(const buttonName);
begin
buttonName[0] := 'Sequence';
buttonName[1] := 'Repetition';
buttonName[2]:= 'Modularisation';
buttonName[3]:= 'Function';
buttonName[4]:= 'Variable';
buttonName[5]:= 'Type';
buttonName[6]:= 'Program';
buttonName[7]:= 'If and case';
buttonName[8]:= 'Procedure';
buttonName[9]:= 'Constant';
buttonName[10]:= 'Array';
buttonName[11]:= 'For, while, repeat';
end;
and in main I am trying to use this for loop
for i:=0 to High(buttonName) do
begin
DrawButton(x, y, buttonName[i]);
y:= y+70;
end;
Please know, I am very new to this and am not too confident of my knowledge in arrays, parameters/calling by constant and such.
Thank you
The parameter definition of PopulateButton() is wrong.
Try this:
type
TButtonNames = array[0..11] of String;
procedure PopulateButtons(var AButtonNames: TButtonNames);
begin
AButtonNames[0] := 'Sequence';
...
end;
...
var lButtonNames: TButtonNames;
PopulateButtons(lButtonNames);
for i := Low(lButtonNames) to High(lButtonNames) do
begin
DrawButton(x, y, lButtonNames[i]);
y:= y+70;
end;
Also pay attention to the naming conventions. Types normally begin with a T and function parameters start with an A.

Pascal runtime error (range overrun) while reading array from file

I am trying to write a program to read a long list of book(1000 books),isbn etc
but when the program runs, it shows range overrun
the format of txt is
1
1234567890
ABC book
peter
20
2
1234567896
...
the code is:
const maxbk=1000;
type bookrecord = record
book_no:string;
isbn:string;
book_name:string;
author:string;
borrowed:string;
end;
var booklist : array[1..maxbk] of bookrecord;totalbook:integer;
procedure readbooklist(var bklist:array of bookrecord;var totalbk:integer);
var f:text;temp:string;code:integer;
begin
totalbk:=0;
assign(f,'bklist.txt');
reset(f);
while not eof(f) do
begin
readln(f,bklist[totalbk+1].book_no);
readln(f,bklist[totalbk+1].isbn);
readln(f,bklist[totalbk+1].book_name);
readln(f,bklist[totalbk+1].author);
readln(f,bklist[totalbk+1].borrowed);
totalbk:=totalbk+1;
end;
close(f);
writeln('read file done');
end;
begin
readbooklist(booklist,totalbook);
end.
who can help to fix the problem??
I think the problem is in your handling of the array parameter. Try this (highlighted in bold are the changes I've added):
const maxbk=1000;
type bookrecord = record
book_no:string;
isbn:string;
book_name:string;
author:string;
borrowed:string;
end;
var booklist : array[1..maxbk] of bookrecord; totalbook:integer;
procedure readbooklist(var bklist:array of bookrecord;var totalbk:integer);
var f:text;temp:string;code:integer;
begin
totalbk:=Low(bklist);
assign(f,'bklist.txt');
reset(f);
while not eof(f) do
begin
readln(f,bklist[totalbk].book_no);
readln(f,bklist[totalbk].isbn);
readln(f,bklist[totalbk].book_name);
readln(f,bklist[totalbk].author);
readln(f,bklist[totalbk].borrowed);
totalbk:=totalbk+1;
end;
totalbk := totalbk - Low(bklist);
close(f);
writeln('read file done');
end;
begin
readbooklist(booklist,totalbook);
end.
Also, a few choice spaces would help with readability (like a space after each comma and around assignment operators).
Note, too, that your code (and the changed code I'm providing) don't check for incomplete records in your input text file or properly check for blank lines, etc (e.g., invalid book_no values). You should attempt to add some code which makes it a little more resilient to problems in the input file. As others have pointed out, there are probably better ways to structure the input and read it as well.

Resources