WeixiangYan/CodeTransOcean huggingface dataset:
Task: Menu








VB: 
Function Menu(ArrList, Prompt)
    Select Case False   
        Case IsArray(ArrList)
           Menu = ""   
           Exit Function
        Case UBound(ArrList) >= LBound(ArrList)
           Menu = ""   
           Exit Function
    End Select
    
    Do While True
        For i = LBound(ArrList) To UBound(ArrList)
            WScript.StdOut.WriteLine((i + 1) & ". " & ArrList(i))
        Next
        WScript.StdOut.Write(Prompt)
        Choice = WScript.StdIn.ReadLine
        
        If IsNumeric(Choice) Then   
            If CStr(CLng(Choice)) = Choice Then   
                Index = Choice - 1   
                
                If LBound(ArrList) <= Index And Index <= UBound(ArrList) Then
                    Exit Do
                End If
            End If
        End If
        WScript.StdOut.WriteLine("Invalid choice.")
    Loop
    Menu = ArrList(Index)
End Function


Sample = Array("fee fie", "huff and puff", "mirror mirror", "tick tock")
InputText = "Which is from the three pigs: "
WScript.StdOut.WriteLine("Output: " & Menu(Sample, InputText))
Task: Menu




Go: package main

import "fmt"

func menu(choices []string, prompt string) string {
    if len(choices) == 0 {
        return ""
    }
    var c int
    for {
        fmt.Println("")
        for i, s := range choices {
            fmt.Printf("%d.  %s\n", i+1, s)
        }
        fmt.Print(prompt)
        _, err := fmt.Scanln(&c)

        if err == nil && c > 0 && c <= len(choices) {
            break
        }
    }
    return choices[c-1]
}

func main() {
    pick := menu(nil, "No prompt")
    fmt.Printf("No choices, result = %q\n", pick)

    choices := []string{
        "fee fie",
        "huff and puff",
        "mirror mirror",
        "tick tock",
    }
    pick = menu(choices, "Enter number: ")
    fmt.Printf("You picked %q\n", pick)
}
Task: Menu



C#: using System;
using System.Collections.Generic;

public class Menu
{
        static void Main(string[] args)
        {
            List<string> menu_items = new List<string>() { "fee fie", "huff and puff", "mirror mirror", "tick tock" };
            
            Console.WriteLine(PrintMenu(menu_items));
            Console.ReadLine();
        }
        private static string PrintMenu(List<string> items)
        {
            if (items.Count == 0)
                return "";

            string input = "";
            int i = -1;
            do
            {
                for (int j = 0; j < items.Count; j++)
                    Console.WriteLine("{0}) {1}", j, items[j]);

                Console.WriteLine("What number?");
                input = Console.ReadLine();

            } while (!int.TryParse(input, out i) || i >= items.Count || i < 0);
            return items[i];
        }
}








Fortran: 


      module menu
      public :: selector
      contains

      function selector(title,options) result(choice)
      character(len=*),intent(in) :: title
      character(len=*),dimension(:),intent(in) :: options
      character(len=len(options)) :: choice
      integer :: i,ichoose,ios,n

      choice = ""

      n = size(options)
      if (n > 0) then
        do
          print "(a)",title
          print "(i8,"", "",a)",(i,options(i),i=1,n)
          read (*,fmt="(i8)",iostat=ios) ichoose

          if (ios == -1) exit 
          if (ios /= 0) cycle 
          if (ichoose < 1) cycle
          if (ichoose > n) cycle 

          choice = options(ichoose)
          exit
        end do
      end if
      end function selector
      end module menu

      program menu_demo
      use menu
      character(len=14),dimension(:),allocatable :: zero_items,fairytale
      character(len=len(zero_items)) :: s

      
      allocate(zero_items(0))
      print "(a)","input items:",zero_items
      s = selector('Choose from the empty list',zero_items)
      print "(a)","returned:",s
      if (s == "") print "(a)","(an empty string)"

      
      allocate(fairytale(4))
      fairytale = (/'fee fie       ','huff and puff ', &
        'mirror mirror ','tick tock     '/)
      print "(a)","input items:",fairytale
      s = selector('Choose a fairy tale',fairytale)
      print "(a)","returned: ",s
      if (s == "") print "(a)","(an empty string)"

      end program menu_demo
Task: Menu


C++: #include <iostream>
#include <string>
#include <vector>

void print_menu(const std::vector<std::string>& terms)
{
    for (size_t i = 0; i < terms.size(); i++) {
        std::cout << i + 1 << ") " << terms[i] << '\n';
    }
}

int parse_entry(const std::string& entry, int max_number)
{
    int number = std::stoi(entry);
    if (number < 1 || number > max_number) {
        throw std::invalid_argument("");
    }

    return number;
}

std::string data_entry(const std::string& prompt, const std::vector<std::string>& terms)
{
    if (terms.empty()) {
        return "";
    }

    int choice;
    while (true) {
        print_menu(terms);
        std::cout << prompt;

        std::string entry;
        std::cin >> entry;

        try {
            choice = parse_entry(entry, terms.size());
            return terms[choice - 1];
        } catch (std::invalid_argument&) {
            
        }
    }
}

int main()
{
    std::vector<std::string> terms = {"fee fie", "huff and puff", "mirror mirror", "tick tock"};
    std::cout << "You chose: " << data_entry("> ", terms) << std::endl;
}









Fortran: 


      module menu
      public :: selector
      contains

      function selector(title,options) result(choice)
      character(len=*),intent(in) :: title
      character(len=*),dimension(:),intent(in) :: options
      character(len=len(options)) :: choice
      integer :: i,ichoose,ios,n

      choice = ""

      n = size(options)
      if (n > 0) then
        do
          print "(a)",title
          print "(i8,"", "",a)",(i,options(i),i=1,n)
          read (*,fmt="(i8)",iostat=ios) ichoose

          if (ios == -1) exit 
          if (ios /= 0) cycle 
          if (ichoose < 1) cycle
          if (ichoose > n) cycle 

          choice = options(ichoose)
          exit
        end do
      end if
      end function selector
      end module menu

      program menu_demo
      use menu
      character(len=14),dimension(:),allocatable :: zero_items,fairytale
      character(len=len(zero_items)) :: s

      
      allocate(zero_items(0))
      print "(a)","input items:",zero_items
      s = selector('Choose from the empty list',zero_items)
      print "(a)","returned:",s
      if (s == "") print "(a)","(an empty string)"

      
      allocate(fairytale(4))
      fairytale = (/'fee fie       ','huff and puff ', &
        'mirror mirror ','tick tock     '/)
      print "(a)","input items:",fairytale
      s = selector('Choose a fairy tale',fairytale)
      print "(a)","returned: ",s
      if (s == "") print "(a)","(an empty string)"

      end program menu_demo
Task: Menu

C: #include <stdio.h>
#include <stdlib.h>
#include <string.h>

const char *menu_select(const char *const *items, const char *prompt);

int
main(void)
{
	const char *items[] = {"fee fie", "huff and puff", "mirror mirror", "tick tock", NULL};
	const char *prompt = "Which is from the three pigs?";

	printf("You chose %s.\n", menu_select(items, prompt));

	return EXIT_SUCCESS;
}

const char *
menu_select(const char *const *items, const char *prompt)
{
	char buf[BUFSIZ];
	int i;
	int choice;
	int choice_max;

	if (items == NULL)
		return NULL;

	do {
		for (i = 0; items[i] != NULL; i++) {
			printf("%d) %s\n", i + 1, items[i]);
		}
		choice_max = i;
		if (prompt != NULL)
			printf("%s ", prompt);
		else
			printf("Choice? ");
		if (fgets(buf, sizeof(buf), stdin) != NULL) {
			choice = atoi(buf);
		}
	} while (1 > choice || choice > choice_max);

	return items[choice - 1];
}










Fortran: 


      module menu
      public :: selector
      contains

      function selector(title,options) result(choice)
      character(len=*),intent(in) :: title
      character(len=*),dimension(:),intent(in) :: options
      character(len=len(options)) :: choice
      integer :: i,ichoose,ios,n

      choice = ""

      n = size(options)
      if (n > 0) then
        do
          print "(a)",title
          print "(i8,"", "",a)",(i,options(i),i=1,n)
          read (*,fmt="(i8)",iostat=ios) ichoose

          if (ios == -1) exit 
          if (ios /= 0) cycle 
          if (ichoose < 1) cycle
          if (ichoose > n) cycle 

          choice = options(ichoose)
          exit
        end do
      end if
      end function selector
      end module menu

      program menu_demo
      use menu
      character(len=14),dimension(:),allocatable :: zero_items,fairytale
      character(len=len(zero_items)) :: s

      
      allocate(zero_items(0))
      print "(a)","input items:",zero_items
      s = selector('Choose from the empty list',zero_items)
      print "(a)","returned:",s
      if (s == "") print "(a)","(an empty string)"

      
      allocate(fairytale(4))
      fairytale = (/'fee fie       ','huff and puff ', &
        'mirror mirror ','tick tock     '/)
      print "(a)","input items:",fairytale
      s = selector('Choose a fairy tale',fairytale)
      print "(a)","returned: ",s
      if (s == "") print "(a)","(an empty string)"

      end program menu_demo
Task: Menu





Java: public static String select(List<String> list, String prompt){
    if(list.size() == 0) return "";
    Scanner sc = new Scanner(System.in);
    String ret = null;
    do{
        for(int i=0;i<list.size();i++){
            System.out.println(i + ": "+list.get(i));
        }
        System.out.print(prompt);
        int index = sc.nextInt();
        if(index >= 0 && index < list.size()){
            ret = list.get(index);
        }
    }while(ret == null);
    return ret;
}






Fortran: 


      module menu
      public :: selector
      contains

      function selector(title,options) result(choice)
      character(len=*),intent(in) :: title
      character(len=*),dimension(:),intent(in) :: options
      character(len=len(options)) :: choice
      integer :: i,ichoose,ios,n

      choice = ""

      n = size(options)
      if (n > 0) then
        do
          print "(a)",title
          print "(i8,"", "",a)",(i,options(i),i=1,n)
          read (*,fmt="(i8)",iostat=ios) ichoose

          if (ios == -1) exit 
          if (ios /= 0) cycle 
          if (ichoose < 1) cycle
          if (ichoose > n) cycle 

          choice = options(ichoose)
          exit
        end do
      end if
      end function selector
      end module menu

      program menu_demo
      use menu
      character(len=14),dimension(:),allocatable :: zero_items,fairytale
      character(len=len(zero_items)) :: s

      
      allocate(zero_items(0))
      print "(a)","input items:",zero_items
      s = selector('Choose from the empty list',zero_items)
      print "(a)","returned:",s
      if (s == "") print "(a)","(an empty string)"

      
      allocate(fairytale(4))
      fairytale = (/'fee fie       ','huff and puff ', &
        'mirror mirror ','tick tock     '/)
      print "(a)","input items:",fairytale
      s = selector('Choose a fairy tale',fairytale)
      print "(a)","returned: ",s
      if (s == "") print "(a)","(an empty string)"

      end program menu_demo
Task: Menu







Python: def _menu(items):
    for indexitem in enumerate(items):
        print ("  %2i) %s" % indexitem)

def _ok(reply, itemcount):
    try:
        n = int(reply)
        return 0 <= n < itemcount
    except:
        return False
    
def selector(items, prompt):
    'Prompt to select an item from the items'
    if not items: return ''
    reply = -1
    itemcount = len(items)
    while not _ok(reply, itemcount):
        _menu(items)
        
        reply = raw_input(prompt).strip()
    return items[int(reply)]

if __name__ == '__main__':
    items = ['fee fie', 'huff and puff', 'mirror mirror', 'tick tock']
    item = selector(items, 'Which is from the three pigs: ')
    print ("You chose: " + item)




Fortran: 


      module menu
      public :: selector
      contains

      function selector(title,options) result(choice)
      character(len=*),intent(in) :: title
      character(len=*),dimension(:),intent(in) :: options
      character(len=len(options)) :: choice
      integer :: i,ichoose,ios,n

      choice = ""

      n = size(options)
      if (n > 0) then
        do
          print "(a)",title
          print "(i8,"", "",a)",(i,options(i),i=1,n)
          read (*,fmt="(i8)",iostat=ios) ichoose

          if (ios == -1) exit 
          if (ios /= 0) cycle 
          if (ichoose < 1) cycle
          if (ichoose > n) cycle 

          choice = options(ichoose)
          exit
        end do
      end if
      end function selector
      end module menu

      program menu_demo
      use menu
      character(len=14),dimension(:),allocatable :: zero_items,fairytale
      character(len=len(zero_items)) :: s

      
      allocate(zero_items(0))
      print "(a)","input items:",zero_items
      s = selector('Choose from the empty list',zero_items)
      print "(a)","returned:",s
      if (s == "") print "(a)","(an empty string)"

      
      allocate(fairytale(4))
      fairytale = (/'fee fie       ','huff and puff ', &
        'mirror mirror ','tick tock     '/)
      print "(a)","input items:",fairytale
      s = selector('Choose a fairy tale',fairytale)
      print "(a)","returned: ",s
      if (s == "") print "(a)","(an empty string)"

      end program menu_demo
Task: Menu








VB: 
Function Menu(ArrList, Prompt)
    Select Case False   
        Case IsArray(ArrList)
           Menu = ""   
           Exit Function
        Case UBound(ArrList) >= LBound(ArrList)
           Menu = ""   
           Exit Function
    End Select
    
    Do While True
        For i = LBound(ArrList) To UBound(ArrList)
            WScript.StdOut.WriteLine((i + 1) & ". " & ArrList(i))
        Next
        WScript.StdOut.Write(Prompt)
        Choice = WScript.StdIn.ReadLine
        
        If IsNumeric(Choice) Then   
            If CStr(CLng(Choice)) = Choice Then   
                Index = Choice - 1   
                
                If LBound(ArrList) <= Index And Index <= UBound(ArrList) Then
                    Exit Do
                End If
            End If
        End If
        WScript.StdOut.WriteLine("Invalid choice.")
    Loop
    Menu = ArrList(Index)
End Function


Sample = Array("fee fie", "huff and puff", "mirror mirror", "tick tock")
InputText = "Which is from the three pigs: "
WScript.StdOut.WriteLine("Output: " & Menu(Sample, InputText))



Fortran: 


      module menu
      public :: selector
      contains

      function selector(title,options) result(choice)
      character(len=*),intent(in) :: title
      character(len=*),dimension(:),intent(in) :: options
      character(len=len(options)) :: choice
      integer :: i,ichoose,ios,n

      choice = ""

      n = size(options)
      if (n > 0) then
        do
          print "(a)",title
          print "(i8,"", "",a)",(i,options(i),i=1,n)
          read (*,fmt="(i8)",iostat=ios) ichoose

          if (ios == -1) exit 
          if (ios /= 0) cycle 
          if (ichoose < 1) cycle
          if (ichoose > n) cycle 

          choice = options(ichoose)
          exit
        end do
      end if
      end function selector
      end module menu

      program menu_demo
      use menu
      character(len=14),dimension(:),allocatable :: zero_items,fairytale
      character(len=len(zero_items)) :: s

      
      allocate(zero_items(0))
      print "(a)","input items:",zero_items
      s = selector('Choose from the empty list',zero_items)
      print "(a)","returned:",s
      if (s == "") print "(a)","(an empty string)"

      
      allocate(fairytale(4))
      fairytale = (/'fee fie       ','huff and puff ', &
        'mirror mirror ','tick tock     '/)
      print "(a)","input items:",fairytale
      s = selector('Choose a fairy tale',fairytale)
      print "(a)","returned: ",s
      if (s == "") print "(a)","(an empty string)"

      end program menu_demo
Task: Menu






PHP: <?php
$stdin = fopen("php://stdin", "r");
$allowed = array(1 => 'fee fie', 'huff and puff', 'mirror mirror', 'tick tock');

for(;;) {
    foreach ($allowed as $id => $name) {
        echo "  $id: $name\n";
    }
    echo "Which is from the four pigs: ";
    $stdin_string = fgets($stdin, 4096);
    if (isset($allowed[(int) $stdin_string])) {
        echo "You chose: {$allowed[(int) $stdin_string]}\n";
        break;
    }
}





Fortran: 


      module menu
      public :: selector
      contains

      function selector(title,options) result(choice)
      character(len=*),intent(in) :: title
      character(len=*),dimension(:),intent(in) :: options
      character(len=len(options)) :: choice
      integer :: i,ichoose,ios,n

      choice = ""

      n = size(options)
      if (n > 0) then
        do
          print "(a)",title
          print "(i8,"", "",a)",(i,options(i),i=1,n)
          read (*,fmt="(i8)",iostat=ios) ichoose

          if (ios == -1) exit 
          if (ios /= 0) cycle 
          if (ichoose < 1) cycle
          if (ichoose > n) cycle 

          choice = options(ichoose)
          exit
        end do
      end if
      end function selector
      end module menu

      program menu_demo
      use menu
      character(len=14),dimension(:),allocatable :: zero_items,fairytale
      character(len=len(zero_items)) :: s

      
      allocate(zero_items(0))
      print "(a)","input items:",zero_items
      s = selector('Choose from the empty list',zero_items)
      print "(a)","returned:",s
      if (s == "") print "(a)","(an empty string)"

      
      allocate(fairytale(4))
      fairytale = (/'fee fie       ','huff and puff ', &
        'mirror mirror ','tick tock     '/)
      print "(a)","input items:",fairytale
      s = selector('Choose a fairy tale',fairytale)
      print "(a)","returned: ",s
      if (s == "") print "(a)","(an empty string)"

      end program menu_demo
Task: Menu





Java: public static String select(List<String> list, String prompt){
    if(list.size() == 0) return "";
    Scanner sc = new Scanner(System.in);
    String ret = null;
    do{
        for(int i=0;i<list.size();i++){
            System.out.println(i + ": "+list.get(i));
        }
        System.out.print(prompt);
        int index = sc.nextInt();
        if(index >= 0 && index < list.size()){
            ret = list.get(index);
        }
    }while(ret == null);
    return ret;
}





COBOL:        IDENTIFICATION DIVISION.
       PROGRAM-ID. Test-Prompt-Menu.

       DATA DIVISION.
       WORKING-STORAGE SECTION.

       01  Num-Options    USAGE UNSIGNED-INT VALUE 4.
       01  Example-Menu.
           03  Example-Options-Data.
               05  FILLER PIC X(30) VALUE "fee fie".
               05  FILLER PIC X(30) VALUE "huff and puff".
               05  FILLER PIC X(30) VALUE "mirror mirror".
               05  FILLER PIC X(30) VALUE "tick tock".

           03  Example-Options-Values REDEFINES Example-Options-Data.
               05  Example-Options PIC X(30) OCCURS 4 TIMES.

       01  Chosen-Option PIC X(30).

       PROCEDURE DIVISION.
           CALL "Prompt-Menu" USING BY CONTENT Num-Options
               BY CONTENT Example-Menu
               BY REFERENCE Chosen-Option

           DISPLAY "You chose: " Chosen-Option

           GOBACK
           .

       END PROGRAM Test-Prompt-Menu.

       IDENTIFICATION DIVISION.
       PROGRAM-ID. Prompt-Menu.

       DATA DIVISION.
       LOCAL-STORAGE SECTION.
       01  User-Input        USAGE UNSIGNED-INT.
       01  Input-Flag        PIC X.
           88  Valid-Input   VALUE "Y".

       01  Options-Index     USAGE UNSIGNED-INT.
       01  Index-Display     PIC Z(10).

       LINKAGE SECTION.

       01  Num-Options       USAGE UNSIGNED-INT.
       01  Menu-Options.
           03  Options-Table PIC X(30) OCCURS 0 TO 10000000 TIMES
               DEPENDING ON Num-Options.

       01  Chosen-Option     PIC X(30).

       PROCEDURE DIVISION USING Num-Options Menu-Options Chosen-Option.
       Main.
           IF Num-Options = 0
               MOVE SPACES TO Chosen-Option
               GOBACK
           END-IF

           PERFORM UNTIL Valid-Input
               PERFORM Display-Menu-Options

               DISPLAY "Choose an option: " WITH NO ADVANCING
               ACCEPT User-Input

               PERFORM Validate-Input
           END-PERFORM

           MOVE Options-Table (User-Input) TO Chosen-Option

           GOBACK
           .

       Display-Menu-Options.
           PERFORM VARYING Options-Index FROM 1 BY 1
                   UNTIL Num-Options < Options-Index
               MOVE Options-Index TO Index-Display
               DISPLAY
                   Index-Display ". " Options-Table (Options-Index)
               END-DISPLAY
           END-PERFORM
           .

       Validate-Input.
           IF User-Input = 0 OR > Num-Options
               DISPLAY "Invalid input."
           ELSE
               SET Valid-Input TO TRUE
           END-IF
           .

       END PROGRAM Prompt-Menu.
Task: Menu






PHP: <?php
$stdin = fopen("php://stdin", "r");
$allowed = array(1 => 'fee fie', 'huff and puff', 'mirror mirror', 'tick tock');

for(;;) {
    foreach ($allowed as $id => $name) {
        echo "  $id: $name\n";
    }
    echo "Which is from the four pigs: ";
    $stdin_string = fgets($stdin, 4096);
    if (isset($allowed[(int) $stdin_string])) {
        echo "You chose: {$allowed[(int) $stdin_string]}\n";
        break;
    }
}
Task: Menu






PHP: <?php
$stdin = fopen("php://stdin", "r");
$allowed = array(1 => 'fee fie', 'huff and puff', 'mirror mirror', 'tick tock');

for(;;) {
    foreach ($allowed as $id => $name) {
        echo "  $id: $name\n";
    }
    echo "Which is from the four pigs: ";
    $stdin_string = fgets($stdin, 4096);
    if (isset($allowed[(int) $stdin_string])) {
        echo "You chose: {$allowed[(int) $stdin_string]}\n";
        break;
    }
}






Ada: with ada.text_io,Ada.Strings.Unbounded; use  ada.text_io, Ada.Strings.Unbounded;

procedure menu is 
	type menu_strings is array (positive range <>) of Unbounded_String ;
	function "+" (s : string) return Unbounded_String is (To_Unbounded_String (s));

	function choice (m : menu_strings; prompt : string) return string is
	begin
		if m'length > 0 then
			loop 
				put_line (prompt);
				for i in m'range loop
					put_line (i'img &") " & To_String (m(i)));
				end loop;
				begin
					return To_String (m(positive'value (get_line)));
					exception when others => put_line ("Try again !");
				end;
			end loop;
		end if;
		return "";
	end choice;

begin
	put_line ("You chose " & 
		choice ((+"fee fie",+"huff and puff",+"mirror mirror",+"tick tock"),"Enter your choice "));
end menu;