gpt4 book ai didi

command-line-arguments - 帕斯卡命令行参数

转载 作者:行者123 更新时间:2023-12-03 19:40:56 24 4
gpt4 key购买 nike

我是帕斯卡新手,我有一个给出结果的程序......我需要在给定的变量 ip1 和 ip2 中传递命令行输入。可以通过ParamStr[1]实现,但是不起作用。

  program main;
var
output : integer;
var
ip1 : integer;
var
ip2 : integer;

function add(input1,input2:integer) : integer;
var
result: integer;
begin
if (input1 > input2) then
result := input1
else
result := input2;
add := result;
end;

begin
ip1 := 2533;**{ command line input}**
ip2 := 555;**{ command line input}**

output := add(ip1,ip2);
writeln( ' output : ', output );
end.K

最佳答案

正如另一个答案所说,您使用 ParamCountParamStr 来访问命令行参数。

ParamCount 返回在命令行上传递的参数数量,因此您应该首先检查它以查看是否收到了足够的信息。

ParamStr 允许您访问传递的每个参数。 ParamStr(0) 始终为您提供正在执行的程序的全名(包括路径)。使用传递参数的顺序检索其他参数,ParamStr(1) 是第一个,ParamStr(ParamCount) 是最后一个。使用 ParamStr 接收的每个值都是字符串值,因此必须先将其转换为适当的类型,然后才能使用它。

这是一个工作示例(非常简单,并且省略了所有错误检查 - 例如,如果提供的内容无法转换为整数,您应该使用 StrToInt 保护代码来处理错误)。

program TestParams;

uses
SysUtils;

var
Input1, Input2, Output: Integer;

begin
if ParamCount > 1 then
begin
Input1 := StrToInt(ParamStr(1));
Input2 := StrToInt(ParamStr(2));
Output := Input1 + Input2;
WriteLn(Format('%d + %d = %d', [Input1, Input2, Output]));
end
else
begin
WriteLn('Syntax: ', ParamStr(0)); { Just to demonstrate ParamStr(0) }
WriteLn('There are two parameters required. You provided ', ParamCount);
end;
WriteLn('Press ENTER to exit...');
ReadLn;
end.

不带参数(或仅一个)调用它会显示以下内容:

C:\Temp>TestParams
Syntax: C:\Temp\TestParams.exe
There are two parameters required. You provided 0
Press ENTER to exit...

C:\Temp>TestParams 2
Syntax: C:\Temp>TestParams.exe 2
There are two parameters required. You provided 1
Press ENTER to exit...

使用两个参数调用它会显示

C:\Temp\TestParams 2 2
2 + 2 = 4
Press ENTER to exit...

关于command-line-arguments - 帕斯卡命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25891529/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com