I can't get this program to compile because it doesn't seem to print integer variables along with strings in the Put_Line method. I've looked at source code online and it works when they do it so where am I going wrong. Thanks for your help.
with Ada.Text_IO; use Ada.Text_IO;with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;procedure MultiplicationTable isprocedure Print_Multiplication_Table(Number :in Integer; Multiple :in Integer) isResult : Integer; beginfor Count in 1 ..MultipleloopResult := Number * Count;Put_Line(Number & " x " & Count & " = " & Result);end loop; end Print_Multiplication_Table;Number : Integer;Multiple : Integer;beginPut("Display the multiplication of number: ");Get(Number);Put("Display Multiplication until number: ");Get(Multiple);Print_Multiplication_Table(Number,Multiple);end MultiplicationTable;`
Best Answer
The problem is that you're using & with strings and integers.Try one of the following:
Replace Number
inside the parameter of put with Integer'Image(Number)
Or break up the Put_Line
into the components that you want; ex:
-- Correction to Put_Line(Number & " x " & Count & " = " & Result);Put( Number );Put( " x " );Put( Count );Put( " = " );Put( Result);New_Line(1);
Try this:
Put_Line(Integer'Image(Number) & " x " & Integer'Image(Count) & " = " & Integer'Image(Result));
You're already have with
and use
clauses for Ada.Integer_Text_IO
, but you're not actually using it.
Change this:
Put_Line(Number & " x " & Count & " = " & Result);
to this:
Put(Number); Put(" x "); Put(Count); Put(" = "); Put(Result); New_Line;
(I normally wouldn't put multiple statements on one line, but in this case it makes sense.)
Note that Integer'Image
prepends non-negative integers with a space, something I've always found greatly annoying; Ada.Integer_Text_IO.Put
doesn't do that (unless you ask it to).
You could define overloaded "&"
functions, something like this:
function "&"(Left: String; Right: Integer) return String isbeginreturn Left & Integer'Image(Right);end "&";function "&"(Left: Integer; Right: String) return String isbeginreturn Integer'Image(Left) & Right;end "&";
which would make your original Put_Line
call valid, but the multiple Put
calls are probably better style.
Building on the answer (and a comment in another question) from Keith Thompson, here is a full Ada program that can output strings and integers with &
, using Put_Line
, but without the spaces that Integer'Image
would otherwise prepend:
with Ada.Text_IO; use Ada.Text_IO;with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;procedure Main isfunction lstrip(S: String) return String isbeginif S(S'First) = ' ' thenreturn S(S'First+1 .. S'Last);elsereturn S;end if;end;function "&"(Left: String; Right: Integer) return String isbeginreturn Left & lstrip(Integer'Image(Right));end "&";function "&"(Left: Integer; Right: String) return String isbeginreturn lstrip(Integer'Image(Left)) & Right;end "&";beginPut_Line("x=" & 42);end Main;