当我编译以下代码时,我收到错误。我不明白他们中的一些。
代码
program Lasagna;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes, SysUtils
{ you can add units after this };
{$R *.res}
type
TVehicle = record
kindOfVehicle : String[30];
numberOfWheels : Integer;
horsePower : Real;
end;
var
F: file of TVehicle;
Vehicle : Array [1..3] of TVehicle;
index : Integer;
begin
writeln('A RECORD OF DIFFERENT KIND OF VEHICLES.');
writeln('---------------------------------------');
writeln;
AssignFile(F,'C:/Users/W/Desktop/CarRecord.dat');
writeln('Searching for file.');
if FileExists('C:/Users/W/Desktop/CarRecord.dat') then
begin
writeln('File found. Opening file.');
Rewrite(F);
writeln('File ready.');
writeln;
writeln;
for index:=0 to 3 do
begin
writeln('Enter the following details for vehicle no. ',index);
write('Kind of Vehicle: ');
readln(Vehicle[index].kindOfVehicle);
write(F,Vehicle[index].kindOfVehicle);//line 45: this is a string so why do I get an error?**
{Do NOT use writeln() when writing to random access files.}
write('Number of Wheels: ');
readln(Vehicle[index].numberOfWheels);
write(F,IntToStr(Vehicle[index].numberOfWheels));//line 51: The int is converted to string, so i shouldn't get an error?
write('Horse Power of Vehicle: ');
readln(Vehicle[index].horsePower);
write(F, RealToStr(Vehicle[index].horsePower));//line 55:
end;
writeln('Done. Closing File.');
CloseFile(F);
end
else
Rewrite(F);
CloseFile(F);
writeln('File Not Found.');
Writeln('Press ANY key to close the program.');
Readln;
end.
错误
编译Lasagna.lpr
Lasagna.lpr(45,49)错误:不兼容的类型:得到“ShortString” 预计“TVehicle”
Lasagna.lpr(51,60)错误:不兼容的类型:得到“AnsiString” 预计“TVehicle”
Lasagna.lpr(55,59)错误:不兼容的类型:得到“AnsiString” 预计“TVehicle”
Lasagna.lpr(70)致命:编译模块有3个错误,停止
答案 0 :(得分:1)
在这三种情况下,你尝试将一个字符串写入F,它被声明为TVehicle的文件,因此编译器是正确的。
要修复它,您应该将每个字段读入正确类型的变量,用这些变量填充TVehicle类型变量,或者直接使用TVehicle结构的字段并将该变量写入文件。沿着这些方向的东西(我的Pascal有点生锈,很可能在没有碰到它的情况下编译):
var intermediateVehicle : TVehicle;
....
write('Kind of Vehicle: ');
readln(intermediateVehicle.kindOfVehicle);
write('Number of Wheels: ');
readln(intermediateVehicle.numberOfWheels);
write('Horse Power of Vehicle: ');
readln(intermediateVehicle.horsePower);
write(F,intermediateVehicle);
当然,仍然需要添加错误检查......
答案 1 :(得分:1)
在第21行中,您将F声明为“TVehicle文件”。所以,你应该把TVehicle数据写入它,而不是字符串。