首次编写Ada程序遇输出异常求助:部分变量输出异常
Fixing Your First Ada Program's Input/Output Issues
Hey there! Let's break down why your Ada program is acting weird and get it working properly. I can spot a few key issues with your code that are causing the wonky output and missing variable displays:
Key Problems in Your Current Code
- Fixed-length
Stringlimitations: You declaredAuthor,Title, andPagesasString := " "— this creates strings with a fixed length of 1. When you useGet(Author), it can only read 1 character from your input, which is why the first output looks messed up. Any extra characters you type get stuck in the input buffer, so subsequentGetcalls just grab those leftover characters instead of waiting for your new input. - Wrong type for
Pages: You're trying to input a number of pages, butPagesis aStringinstead of a numeric type likeInteger. This makes no sense for a count and will cause issues if you ever want to do math with it later. - Incomplete code: Your snippet cuts off before reading
Pagesand has no output statements or closingend;— that alone would cause compilation or runtime errors.
Corrected Program
Here's a revised version that fixes all these issues, using Ada's unbounded strings for flexible text input and proper integer handling for pages:
with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; procedure Main is Author : Unbounded_String; Title : Unbounded_String; Pages : Integer; begin Put("Enter Author: "); Author := To_Unbounded_String(Get_Line); -- Reads entire line of input Put("Enter Title: "); Title := To_Unbounded_String(Get_Line); Put("Enter number of pages: "); Get(Pages); -- Reads integer input Skip_Line; -- Clears the newline left in the buffer -- Print out the collected info New_Line; Put_Line("Book Details:"); Put_Line("Author: " & To_String(Author)); Put_Line("Title: " & To_String(Title)); Put("Pages: "); Put(Pages, Width => 1); New_Line; end Main;
What Changed & Why
- Unbounded strings:
Unbounded_Stringlets you read input of any length (instead of being stuck with a fixed 1-character limit).Get_Linereads an entire line of text until you press Enter, which is exactly what you want for author names and titles. - Integer for Pages: We switched
PagestoIntegerand usedAda.Integer_Text_IO.Getto properly read numeric input. TheSkip_Linecall clears the newline character left in the buffer after entering the number, so nothing gets messed up if you add more input later. - Proper output: Added
Put_LineandPutstatements to display all the collected data clearly. We convertUnbounded_Stringback to regularStringwithTo_Stringwhen printing.
Give this a try — it should let you input full names/titles, read the page count correctly, and output everything as expected!
内容的提问来源于stack exchange,提问作者No longer in college
相关产品推荐
相关产品推荐

