Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ada string comparison

I am new to Ada and currently trying to write a simple program involving an if-else if statement. The code is as follows:

with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
procedure Year_Codes is

  Year : String(1..9) := "         ";
  CharsRead : Natural;

  function YearCode(Name : in String) return Integer is
  begin
    if(Name = "freshman")then
      return 1;
    elsif(Name = "sophomore")then
      return 2;
    elsif(Name = "junior")then
      return 3;
    elsif(Name = "senior")then
      return 4;
    else
      return 0;
    end if;
  end YearCode;


begin
  Put("Enter your academic year: ");           -- Prompt for input
  Get_Line(Year, CharsRead);                   -- Input
  Put( YearCode(Year) );                       -- Convert and output
  New_Line;
end Year_Codes;

I am getting 0 for every answer. Any input on what I am doing wrong?

like image 339
ola Avatar asked Dec 13 '25 13:12

ola


1 Answers

The "=" operation on strings compares the entire strings. If the user's input is "freshman", the value of Name will be "freshman ", not "freshman". Read the documentation for the Get_Line procedure.

You should probably pass YearCode a slice of the Year string, not the entire string; CharsRead tells you what that slice should be.

Specifically, the call should be:

Put( YearCode(Year(Year'First..CharsRead)) );
like image 142
Keith Thompson Avatar answered Dec 15 '25 14:12

Keith Thompson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!