2013-07-22 62 views
0

我在嘗試將一個ada程序的命令行參數賦值給字符串變量時遇到了一些問題。將CLI參數賦值給Ada中的字符串變量

這裏是我的主要程序:

with Ada.Command_Line; use Ada.Command_Line; 

procedure proc is 
    cli_exception : exception; 
    filename : String (1..Argument(1)'length); 
    usage : String (1..31); 
begin 
    usage := "Usage: ./proc [filename]"; 

    if Argument_Count /= 1 then 
     raise cli_exception; 
    end if; 

    for arg in 1..Argument_Count loop 
     case arg is 
      when 1 => 
       filename := Argument(arg); 
      when others => 
       null; 
     end case; 
    end loop; 

    put_line("filename is: " & filename); 
exception 
    when e: cli_exception => 
     put_line(usage); 
end proc; 

這裏的問題是在上界爲字符串「文件名」中規定的程序的聲明部分。如果沒有給出CLI參數,則參數(1)將在過程開始之前拋出異常,因爲沒有參數#1。

輸出是:

raised CONSTRAINT_ERROR : a-comlin.adb:65 explicit raise 

是否有定義該字符串變量的大小,而無需使用無界字符串的任何其他方式,並沒有選擇任意的號碼(如完全合格的文件名可以得到相當大) ?

-Thanks

+0

爲什麼排除Unbounded_String?它們非常適合處理可變長度的字符串。用普通的字符串來回轉換很簡單。 –

回答

3

使用聲明塊你的過程中,並初始化filename與參數值:

-- ... 
if Argument_Count /= 1 then 
    raise cli_exception; 
end if; 

declare 
    filename : String := Argument (1); 
begin 
    -- do what you want with the filename here. 
end; 

順便說一句,你可以做同樣的usage

usage : String := "Usage: ./proc [filename]"; 

這樣,每次更改字符串時都不必計算字符數。

+4

如果可以的話,使用'constant':'usage:constant String:= ...'。 –