User Input: Difference between revisions

From Rosetta Code
Content added Content deleted
No edit summary
Line 220: Line 220:


=={{header|Modula-3}}==
=={{header|Modula-3}}==
<lang modula3>
<lang modula3>MODULE Input EXPORTS Main;
MODULE Input EXPORTS Main;


IMPORT IO, Fmt;
IMPORT IO, Fmt;

Revision as of 14:32, 13 March 2009

Task
User Input
You are encouraged to solve this task according to the task description, using any language you may know.

In this task, the goal is to input a string and the integer 75000, from the normal user interface.

Text Terminal

Ada

Works with: GCC version 4.1.2

<lang ada>

  function Get_String return String is
    Line : String (1 .. 1_000);
    Last : Natural;
  begin
    Get_Line (Line, Last);
    return Line (1 .. Last);
  end Get_String;
  function Get_Integer return Integer is
    S : constant String := Get_String;
  begin
    return Integer'Value (S);
    --  may raise exception Constraint_Error if value entered is not a well-formed integer
  end Get_Integer;
</lang>

The functions above may be called as shown below <lang ada>

  My_String  : String  := Get_String;
  My_Integer : Integer := Get_Integer;

</lang>

ALGOL 68

print("Enter a string: ");
STRING s := read string;
print("Enter a number: ");
INT i := read int;
~

BASIC

Works with: QuickBasic version 4.5
 INPUT "Enter a string: ", s$
 INPUT "Enter a number: ", i%
Works with: FreeBASIC
 dim s as string
 dim i as integer
 
 input "Enter a string: ", s
 input "Enter the integer 75000: ", i

Befunge

This prompts for a string and pushes it to the stack a character at a time (~) until end of input (-1).

<>:v:"Enter a string: "
 ^,_ >~:1+v
     ^    _@

Numeric input is easier, using the & command.

<>:v:"Enter a number: "
 ^,_ & @

C

Works with: gcc

<lang c> #include <stdio.h>

int main(int argc, char* argv[])
{
        int input;
        if((scanf("%d", &input))==1)
        {
                printf("Read in %d\n", input);
                return 1;
        }
        return 0;
}</lang>

C++

Works with: g++

<lang cpp> #include <iostream>

#include <istream>
#include <ostream>
#include <string>
using namespace std;

int main()
{
     // while probably all current implementations have int wide enough for 75000, the C++ standard
     // only guarantees this for long int.
     long int integer_input;
     string string_input;
     cout << "Enter an integer:  ";
     cin >> integer_input;
     cout << "Enter a string:  ";
     cin >> string_input;
     return 0;
}</lang>

Note: The program as written above only reads the string up to the first whitespace character. To get a complete line into the string, replace <lang cpp> cin >> string_input;</lang> with <lang cpp> readline(cin, string_input);</lang>

C#

<lang csharp> using System;

 namespace C_Sharp_Console {
 
     class example {
 
         static void Main() {
             string word;
             int num;
             
             Console.Write("Enter an integer: ");
             num = Console.Read();
             Console.Write("Enter a String: ");
             word = Console.ReadLine();
         }
     }
 }</lang>

D

<lang D>import tango.io.Console; import Integer = tango.text.convert.Integer;

void main() {

 int num;
 char[] word;
 Cout("Enter an integer:")();
 num = Integer.parse(Cin.get());
 Cout("Enter a string:")();
 word = Cin.get();
}</lang>


Erlang

<lang erlang> {ok, [String]} = io:fread("Enter a string: ","~s").

{ok, [Number]} = io:fread("Enter a number: ","~d").</lang>

Alternatively, you could use io:get_line to get a string: <lang erlang> String = io:get_line("Enter a string: ").</lang>

Forth

Input a string

<lang forth> : INPUT$ ( n -- addr n )

   PAD SWAP ACCEPT
   PAD SWAP ;</lang>

Input a number

The only ANS standard number interpretation word is >NUMBER ( ud str len -- ud str len ), which is meant to be the base factor for more convenient (but non-standard) parsing words. <lang forth> : INPUT# ( -- u true | false )

  0. 16 INPUT$ DUP >R
  >NUMBER NIP NIP 
  R> <> DUP 0= IF NIP THEN ;</lang>
Works with: GNU Forth

<lang forth> : INPUT# ( -- n true | d 1 | false )

   16 INPUT$ SNUMBER? ;</lang>
Works with: Win32Forth

<lang forth> : INPUT# ( -- n true | false )

   16 INPUT$ NUMBER? NIP
   DUP 0= IF NIP THEN ;</lang>

Note that NUMBER? always leaves a double result on the stack. INPUT# returns a single precision number. If you desire a double precision result, remove the NIP.

Here is an example that puts it all together:

<lang forth> : TEST

  ." Enter your name: " 80 INPUT$ CR
  ." Hello there, " TYPE CR
  ." Enter a number: " INPUT# CR
  IF   ." Your number is " .
  ELSE ." That's not a number!" THEN CR ;</lang>

Groovy

<lang groovy> word = System.in.readLine()

num = System.in.readLine().toInteger()</lang>


Haskell

<lang haskell> main = do

    putStr "Enter a string: "
    str <- getLine
    putStr "Enter an integer: "
    num <- readLn :: IO Int 
    putStrLn $ str ++ (show num)</lang>

Note: :: IO Int is only there to disambiguate what type we wanted from read. If num were used in a numerical context, its type would have been inferred by the interpreter/compiler.

Java

<lang java> import java.io.BufferedReader;

import java.io.InputStreamReader;

public class GetInput {
    public static void main(String[] args) throws Exception {
        BufferedReader sysin = new BufferedReader(new InputStreamReader(System.in));
        int number = Integer.parseInt(sysin.readLine());
        String string = sysin.readLine();
    }
}</lang>

or

Works with: Java version 1.5/5.0+

<lang java> import java.util.Scanner;

Scanner stdin = new Scanner(System.in);
String string = stdin.nextLine();
int number = stdin.nextInt();</lang>

Logo literals may be read from a line of input from stdin as either a list or a single word. <lang logo> make "input readlist  ; in: string 75000

show map "number? :input  ; [false true]

make "input readword   ; in: 75000
show :input + 123       ; 75123 
make "input readword   ; in: string 75000
show :input             ; string 75000</lang>

mIRC Scripting Language

alias askmesomething {
  echo -a You answered: $input(What's your name?, e)
}

Modula-3

<lang modula3>MODULE Input EXPORTS Main;

IMPORT IO, Fmt;

VAR string: TEXT;

   number: INTEGER;

BEGIN

 IO.Put("Enter a string: ");
 string := IO.GetLine();
 IO.Put("Enter a number: ");
 number := IO.GetInt();
 IO.Put("You entered: " & string & " and " & Fmt.Int(number) & "\n");

END Input. </lang>

newLISP

Works with: newLISP version 9.0
(print "Enter an integer: ")
(set 'x (read-line))
(print "Enter a string: ")
(set 'y (read-line))

OCaml

<lang ocaml>print_string "Enter a string: "; let str = read_line () in

 print_string "Enter an integer: ";
 let num = read_int () in
   Printf.printf "%s%d\n" str num</lang>

Pascal

<lang pascal> program UserInput(input, output);

var i : Integer;
    s : String;
begin
 write('Enter an integer: ');
 readln(i);
 write('Enter a string: ');
 readln(s)
end.</lang>

Perl

Works with: Perl version 5.8.8

<lang perl> #!/usr/bin/perl

my $string = <>; # equivalent to readline(*STDIN)
my $integer = <>;</lang>

PHP

Works with: CLI SAPI

<lang php> #!/usr/bin/php

<?php
$string = fgets(STDIN);
$integer = (int) fgets(STDIN);</lang>

Pop11

<lang pop11> ;;; Setup item reader

lvars itemrep = incharitem(charin);
lvars s, c, j = 0;
;;; read chars up to a newline and put them on the stack
while (charin() ->> c) /= `\n` do j + 1 -> j ; c endwhile;
;;; build the string
consstring(j) -> s;
;;; read the integer
lvars i = itemrep();</lang>

PostScript

Works with: PostScript version level-2

<lang postscript> %open stdin for reading (and name the channel "kbd"):

/kbd (%stdin) (r) file def
%make ten-char buffer to read string into:
/buf (..........) def
%read string into buffer:
kbd buf readline</lang>

At this point there will be two items on the stack: a boolean which is "true" if the read was successful and the string that was read from the kbd (input terminates on a <return>). If the length of the string exceeds the buffer length, an error condition occurs (rangecheck). For the second part, the above could be followed by this:

<lang postscript> %if the read was successful, convert the string to integer:

{cvi} if</lang>

which will read the conversion operator 'cvi' (convert to integer) and the boolean and execute the former if the latter is true.

PowerShell

$string = Read-Host "Input a string"
$number = Read-Host "Input a number"

Python

Input a string

<lang python> string = raw_input("Input a string: ")</lang> In Python 3.0, raw_input will be renamed to input(). The Python 3.0 equivalent would be <lang python> string = input("Input a string: ")</lang>

Input a number

While input() gets a string in Python 3.0, in 2.x it is the equivalent of eval(raw_input(...)). Because this runs arbitrary code, and just isn't nice, it is being removed in Python 3.0. raw_input() is being changed to input() because there will be no other kind of input function in Python 3.0. <lang python> number = input("Input a number: ") # Deprecated, please don't use.</lang> Python 3.0 equivalent: <lang python> number = eval(input("Input a number: ")) # Evil, please don't use.</lang> The preferred way of getting numbers from the user is to take the input as a string, and pass it to any one of the numeric types to create an instance of the appropriate number. <lang python> number = float(raw_input("Input a number: "))</lang> Python 3.0 equivalent: <lang python> number = float(input("Input a number: "))</lang> float may be replaced by any numeric type, such as int, complex, or decimal.Decimal. Each one varies in expected input.

Raven

<lang raven> 'Input a string: ' print expect as str

'Input an integer: ' print expect 0 prefer as num</lang>

Ruby

Works with: Ruby version 1.8.4

<lang ruby> print "Enter a string: "

s = gets
print "Enter an integer: "
i = gets.to_i   # If string entered, will return zero
puts "String  = " + s
puts "Integer = " + i.to_s</lang>

Scheme

The read procedure is R5RS standard, inputs a scheme representation so, in order to read a string, one must enter "hello world" <lang scheme> (define str (read))

 (define num (read))
 (display "String = ") (display str)
 (display "Integer = ") (display num)</lang>

Tcl

Like LISP, there is no concept of a "number" in TCL - the only real variable type is a string (whether a string might represent a number is a matter of interpretation of the string in a mathematical expression at some later time). Thus the input is the same for both tasks:

<lang tcl> set str [gets stdin]

 set num [gets stdin]</lang>

possibly followed by something like

<lang tcl> if {![string is integer $num]} then { ...do something here...}</lang>

Toka

needs readline
." Enter a string: " readline is-data the-string
." Enter a number: " readline >number [ ." Not a number!" drop 0 ] ifFalse is-data the-number
the-string type cr
the-number . cr

UNIX Shell

#!/bin/sh

read STRING
read INTEGER

Works with: Bourne Again SHell
#!/bin/bash

read STRING
read INTEGER

Vedit macro language

Get_Input(1, "Enter a string: ")
#2 = Get_Num("Enter a number: ")

GUI

AppleScript

set input to text returned of (display dialog "Enter text:" default answer "")
set input to text returned of (display dialog "Enter a number:" default answer "") as integer

Java

Library: Swing

<lang java> import javax.swing.*;

public class GetInputSwing {
    public static void main(String[] args) throws Exception {
        int number = Integer.parseInt(JOptionPane.showInputDialog ("Enter an Integer"));
        String string = JOptionPane.showInputDialog ("Enter a String");
    }
}</lang>

Python

Works with: Python version 2.5
Library: Tkinter

<lang python> import tkSimpleDialog

 number = tkSimpleDialog.askinteger("Integer", "Enter a Number")
 string = tkSimpleDialog.askstring("String", "Enter a String")</lang>

Tcl

Library: Tk

<lang tcl> # create entry widget:

 pack [entry .e1]
 # read its content:
 set input [.e get]</lang>

Alternatively, the content of the widget can be tied to a variable:

<lang tcl> pack [entry .e1 -textvar input]

 # show the content at any time by
 puts $input</lang>

The -validate option can be used to test the contents/edits of the widget at any time against any parameters (including testing string is integer when the user hits <Return> or such)

VBScript

 strUserIn = InputBox("Enter Data")
 Wscript.Echo strUserIn

Vedit macro language

Displays a dialog box with two input fields and default OK button. The values entered are stored in text registers 1 and 2. The value from 2nd field is then converted into numeric value. (Accepts integers or integer expressions.)

Dialog_Input_1(1, "`User Input example`,
                   `??Enter a string `,
                   `??Enter a number `") 
#2 = Num_Eval_Reg(2)