ada - 函数从标准输入读取,不带任何 "in"参数

标签 ada

也许这很简单,我只是缺少一些基本信息,但我似乎无法在任何地方找到答案。

我正在为类编写一个 Get_Word 函数,这是我的教授编写的规范文件的相关部分:

function Get_Word return Ustring;
-- return a space-separated word from standard input

procedure Fill_Word_List(Wl : in out Ustring_Vector);
-- read a text file from standard in and add all
-- space-separated words to the word list wl

我已经编写了 Get_Word 函数,并尝试使用以下代码对其进行测试:

with Ada.Text_IO; use Ada.Text_Io;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
procedure ngramtest is

Name : String(1..80);
File : File_Type;
Size : Natural;

function Get_Word return String is
    -- I'm using a strings instead of Unbounded_Strings for testing purposes.
    Word : String(1..80) := (others => ' ');
    Char : Character;
    File : File_Type;
    Eol  : Boolean;
    I    : Integer := 1;
begin
    --this code below, when uncommented reveals whether or not the file is open.
    --if Is_Open(File) then
    --  Word := (1..80 => 'y');
    --else
    --  Word := (1..80 => 'n');
    --end if;
    loop
        Look_Ahead(File, Char, Eol);
        if Eol then
            exit;
        elsif Char = ' ' then
            exit;
        else
            Get (File, Char);
            Word(I) := Char;
            I := I + 1;
        end if;
    end loop;
    return Word(1..Word'Last);
end Get_Word;

begin
    Put ("Enter filename: ");
    Get_Line (Name, Size);
    Open (File, Mode => In_File, Name => Name(1..Size));
    Put (Get_Word);
    Close(File);
end ngramtest;

它可以编译,但在运行时我收到一个异常,告诉我该文件未打开,并且注释掉的部分返回“nnnnnn...”,这意味着该文件未在函数内打开。

我的问题是,如果我不允许在函数中使用参数,我该如何从标准输入中读取内容?没有它们,该函数将无法访问文件。 本质上,我如何“Get_Word”?

抱歉,如果这很简单,但我完全迷路了。

最佳答案

您需要将"file"变量设置为标准输入:

File : File_Type := Ada.Text_IO.Standard_Input;

关于ada - 函数从标准输入读取,不带任何 "in"参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16756254/

相关文章:

ada - Ada:pragma Pure/Remote_Types和系统类型

operators - 为什么 Ada 中没有像 +=、-= 或++ 这样的(增强赋值)运算符?

gcc - Mac OS 的链接器问题

ada - "item"的实际必须是一个变量 - Ada

c - 访问类型的 Ada 数组

STL - 如何在 Ada 中进行 std::rotate?

Ada 中的 boolean 大小

nested - 使用嵌套包类型作为类型的私有(private)部分声明

size - 如何在 Ada 中显式显示泛型类型的大小?

shell - 为什么我的 GNAT 的杰出文件描述符不起作用?