You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ada中Integer'Value实现及定长字符串输入异常修复咨询

Ada输入对比程序非定长适配修复方案

错误原因

原程序定义了定长字符串S : String(1..5),调用Get(S)时会强制读取恰好5个输入字符,不会在空格处截断。当用户输入短于5位的字符串时,空格和后续整数的首位会被一并读入S中,导致Integer'Value转换时因内容含非法字符抛出CONSTRAINT_ERROR。

修复实现

修改思路

  • 使用可变长字符串存储用户输入的第一个参数,自动适配任意输入长度
  • 调整输入读取逻辑,只读取第一个空白分隔符前的内容作为待对比字符串
  • 增加异常捕获逻辑,处理字符串无法转换为整数的异常场景

修复后完整代码

with Ada.Text_IO;         use Ada.Text_IO;                                                                
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Text_IO.Unbounded_IO; use Ada.Text_IO.Unbounded_IO;
 
procedure Test2 is
    
    function String_Integer_Check(
        S : in Unbounded_String;
        I : in Integer) return Boolean is         
    begin
        -- 捕获字符串转整数的格式错误异常
        begin
            return Integer'Value(To_String(S)) = I;
        exception
            when CONSTRAINT_ERROR =>
                Put_Line("提示:输入的第一个参数不是合法整数");
                return False;
        end;
    end String_Integer_Check;
           
    S : Unbounded_String;
    I : Integer;
   
begin
    Put("Type in a string and an integer: ");
    Get(S); -- 自动读取到下一个空白符为止,无长度限制
    Get(I);
    Put("They are ");
   
    if not String_Integer_Check(S, I) then
        Put("not ");
    end if;
   
    Put_Line("the same.");
end Test2;

可选扩展

如果需要保留原需求里的字符串必须为5位的校验规则,可以在String_Integer_Check函数开头增加长度判断:

if Length(S) /= 5 then
    Put_Line("提示:输入的字符串长度必须为5位");
    return False;
end if;

内容的提问来源于stack exchange,提问作者leun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 00:24:04