string - Integer'Value("X") 在 Ada 中的实现
问题描述
我将创建一个带有两个参数的子程序;一个字符串和一个整数。子程序将比较这两者,看看它们是否相同。
例如:
键入一个正好包含 5 个字符的字符串和一个整数:12345 123
-- 用户输入粗体
他们是不一样的!
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
procedure Test2 is
function String_Integer_Check(
S : in String;
I : in Integer) return Boolean is
begin
if Integer'Value(S) = I then
return True;
else
return False;
end if;
end String_Integer_Check;
S : String(1..5);
I : Integer;
begin
Put("Type in a string containing exactly 5 characters, and an integer: ");
Get(S);
Get(I);
Put("They are ");
if String_Integer_Check(S, I) = False then
Put("not ");
end if;
Put("the same.");
end Test2;
我的程序工作,假设用户输入一个 5 个字符的字符串。如果用户不这样做,我的程序将无法运行。我该如何解决?
如果我输入123 1234(字符串是 3 个字符,整数是 4 个数字),我会得到这个错误:
他们是
引发 CONTRAINT_ERROR:“值”的错误输入:“123 1”
解决方案
确保两个输入在不同的线路上。您看到的 I/O 问题是由于在同一输入行上混合了字符串 I/O 和整数 I/O。当输入的字符串部分包含多于或少于 5 个字符时,这是一个问题。
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
procedure value_compare is
str_num : String (1 .. 80);
length : Natural;
num : Integer;
begin
Put ("Enter a 5 digit number: ");
Get_Line (Item => str_num, Last => length);
if length = 5 then
Put ("Enter a number: ");
Get (num);
if num = Integer'Value (str_num(1..Length)) then
Put_Line ("The two values are equal.");
else
Put_Line ("The two values are not equal.");
end if;
else
Put_Line
("The input value " & str_num (1 .. length) &
" does not contain 5 exactly characters.");
end if;
end value_compare;