User input/Text: Difference between revisions

From Rosetta Code
Content added Content deleted
(added APL example)
(→‎{{header|Julia}}: A new entry for Julia)
Line 595: Line 595:
stdin fgets 10 strtol.
stdin fgets 10 strtol.
</lang>
</lang>

=={{header|Julia}}==
<lang Julia>
print("String? ")
y = chomp(readline())
println("Your input was \"", y, "\".\n")
print("Integer? ")
y = chomp(readline())
try
y = parseint(y)
println("Your input was \"", y, "\".\n")
catch
println("Sorry, but \"", y, "\" does not compute as an integer.")
end
</lang>

{{out}}
<pre>
String? cheese
Your input was "cheese".

Integer? 75000
Your input was "75000".

mike@harlan:~/rosetta/julia$ julia user_input_text.jl
String? theory
Your input was "theory".

Integer? 75,000
Sorry, but "75,000" does not compute as an integer.
</pre>


=={{header|Kite}}==
=={{header|Kite}}==

Revision as of 19:40, 8 April 2015

Task
User input/Text
You are encouraged to solve this task according to the task description, using any language you may know.
User input/Text is part of Short Circuit's Console Program Basics selection.

In this task, the goal is to input a string and the integer 75000, from the text console.

See also: User input/Graphical

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

<lang algol68>print("Enter a string: "); STRING s := read string; print("Enter a number: "); INT i := read int; ~</lang>

APL

<lang APL>str←⍞ int←⎕</lang>

AutoHotkey

Windows console

<lang AutoHotkey>DllCall("AllocConsole") FileAppend, please type something`n, CONOUT$ FileReadLine, line, CONIN$, 1 msgbox % line FileAppend, please type '75000'`n, CONOUT$ FileReadLine, line, CONIN$, 1 msgbox % line</lang>

Input Command

this one takes input regardless of which application has focus. <lang AutoHotkey>TrayTip, Input:, Type a string: Input(String) TrayTip, Input:, Type an int: Input(Int) TrayTip, Done!, Input was recieved. Msgbox, You entered "%String%" and "%Int%" ExitApp Return

Input(ByRef Output) {

 Loop
 {
   Input, Char, L1, {Enter}{Space}
   If ErrorLevel contains Enter 
     Break
   Else If ErrorLevel contains Space
     Output .= " "
   Else 
     Output .= Char
   TrayTip, Input:, %Output%
 }

}</lang>

AWK

This demo shows a same-line prompt, and that the integer i becomes 0 if the line did not parse as an integer. <lang awk>~/src/opt/run $ awk 'BEGIN{printf "enter a string: "}{s=$0;i=$0+0;print "ok,"s"/"i}' enter a string: hello world ok,hello world/0 75000 ok,75000/75000</lang>

BASIC

Many BASICs will automatically append a question mark (?) to the end of the prompt if the prompt is followed by a semicolon (;). (Some of those will skip the question mark if the prompt is followed by a comma (,) instead of a semicolon.)

This isn't a hard-and-fast rule -- for example, Chipmunk Basic never appends a question mark.

<lang qbasic>INPUT "Enter a string"; s$ INPUT "Enter a number: ", i%</lang>

Output (QBasic):

Enter a string? foo
Enter a number: 1

Applesoft BASIC

<lang basic>10 INPUT "ENTER A STRING: "; S$ 20 INPUT "ENTER A NUMBER: "; I : I = INT(I)</lang>

Batch File

<lang dos>@echo off set /p var= echo %var% 75000</lang>

BBC BASIC

<lang bbcbasic> INPUT LINE "Enter a string: " string$

     INPUT "Enter a number: " number
     
     PRINT "String = """ string$ """"
     PRINT "Number = " ; number</lang>

Befunge

This prompts for a string and pushes it to the stack a character at a time (~) until end of input (-1). <lang befunge><>:v:"Enter a string: "

^,_ >~:1+v
    ^    _@</lang>

Numeric input is easier, using the & command. <lang befunge><>:v:"Enter a number: "

^,_ & @</lang>

Bracmat

<lang bracmat>( doit = out'"Enter a string"

 & get':?mystring
 &   whl
   ' ( out'"Enter a number"
     & get':?mynumber
     & !mynumber:~#
     & out'"I said:\"a number\"!"
     )
 & out$(mystring is !mystring \nmynumber is !mynumber \n)

);</lang>

{?} !doit
Enter a string
abacus
Enter a number
75000h
I said:"a number"!
Enter a number
75000
mystring is abacus
mynumber is 75000

C

<lang c>#include <stdio.h>

  1. include <stdlib.h>

int main(void) {

   // Get a string from stdin
   char str[BUFSIZ];
   puts("Enter a string: ");
   fgets(str, sizeof(str), stdin);
   // Get 75000 from stdin
   long num;
   char buf[BUFSIZ];
   do
   {
       puts("Enter 75000: ");
       fgets(buf, sizeof(buf), stdin);
       num = strtol(buf, NULL, 10);
   } while (num != 75000);
   return EXIT_SUCCESS;

}</lang>

C++

Works with: g++

<lang cpp>#include <iostream>

  1. 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> getline(cin, string_input);</lang>

Note: if a numeric input operation fails, the value is not stored for that operation, plus the fail bit is set, which causes all future stream operations to be ignored (e.g. if a non-integer is entered for the first input above, then nothing will be stored in either the integer and the string). A more complete program would test for an error in the input (with if (!cin) // handle error) after the first input, and then clear the error (with cin.clear()) if we want to get further input.

Alternatively, we could read the input into a string first, and then parse that into an int later.

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>

Clojure

<lang lisp>(import '(java.util Scanner)) (def scan (Scanner. *in*)) (def s (.nextLine scan)) (def n (.nextInt scan))</lang>

COBOL

Works with: OpenCOBOL

<lang cobol> IDENTIFICATION DIVISION.

      PROGRAM-ID. Get-Input.
      DATA DIVISION.
      WORKING-STORAGE SECTION.
      01  Input-String PIC X(30).
      01  Input-Int    PIC 9(5).
      PROCEDURE DIVISION.
      DISPLAY "Enter a string:"
      ACCEPT Input-String
      DISPLAY "Enter a number:"
      ACCEPT Input-Int
      GOBACK
      .</lang>

Common Lisp

<lang lisp>(format t "Enter some text: ") (let ((s (read-line)))

   (format t "You entered ~s~%" s))

(format t "Enter a number: ") (let ((n (read)))

   (if (numberp n)
       (format t "You entered ~d.~%" n)
     (format t "That was not a number.")))</lang>

D

<lang D>import std.stdio;

void main() {

   long number;
   write("Enter an integer: ");
   readf("%d", &number);
   
   char[] str;
   write("Enter a string: ");
   readf(" %s\n", &str);

   writeln("Read in '", number, "' and '", str, "'");

}</lang>

Delphi

<lang Delphi>program UserInputText;

{$APPTYPE CONSOLE}

uses SysUtils;

var

 s: string;
 lStringValue: string;
 lIntegerValue: Integer;

begin

 WriteLn('Enter a string:');
 Readln(lStringValue);
 repeat
   WriteLn('Enter the number 75000');
   Readln(s);
   lIntegerValue := StrToIntDef(s, 0);
   if lIntegerValue <> 75000 then
     Writeln('Invalid entry: ' + s);
 until lIntegerValue = 75000;

end.</lang>

Déjà Vu

<lang dejavu>input s:

   !print\ s
   !decode!utf-8 !read-line!stdin

local :astring input "Enter a string: " true while:

   try:
       to-num input "Enter the number 75000: "
       /= 75000
   catch value-error:
       true</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>

Euphoria

<lang Euphoria>include get.e

sequence s atom n

s = prompt_string("Enter a string:") puts(1, s & '\n') n = prompt_number("Enter a number:",{}) printf(1, "%d", n)</lang>

Factor

<lang factor>"Enter a string: " write readln "Enter a number: " write readln string>number</lang>

Falcon

<lang falcon>printl("Enter a string:") str = input() printl("Enter a number:") n = int(input())</lang>

FALSE

FALSE has neither a string type nor numeric input. Shown instead are routines to parse and echo a word and to parse and interpret a number using the character input command (^). <lang false>[[^$' =~][,]#,]w: [0[^'0-$$9>0@>|~][\10*+]#%]d: w;! d;!.</lang>

Fantom

The 'toInt' method on an input string will throw an exception if the input is not a number.

<lang fantom> class Main {

 public static Void main ()
 {
   Env.cur.out.print ("Enter a string: ").flush
   str := Env.cur.in.readLine
   echo ("Entered :$str:")
   Env.cur.out.print ("Enter 75000: ").flush
   Int n
   try n = Env.cur.in.readLine.toInt
   catch (Err e) 
   {
     echo ("You had to enter a number")
     return
   }
   echo ("Entered :$n: which is " + ((n == 75000) ? "correct" : "wrong"))
 }

} </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.

Works with: 4tH

<lang forth>: input#

 begin
   refill drop bl parse-word          ( a n)
   number error?                      ( n f)
 while                                ( n)
   drop                               ( --)
 repeat                               ( n)
</lang>

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>

Fortran

Works with: Fortran version 90 and later

<lang fortran>character(20) :: s integer :: i

print*, "Enter a string (max 20 characters)" read*, s print*, "Enter the integer 75000" read*, i</lang>

Go

Go has C-like Scan and Scanf functions for quick and dirty input: <lang go>package main

import "fmt"

func main() {

   var s string
   var i int
   if _, err := fmt.Scan(&s, &i); err == nil && i == 75000 {
       fmt.Println("good")
   } else {
       fmt.Println("wrong")
   }

}</lang> Code below allows much more control over interaction and error checking. <lang go> package main

import (

   "bufio"
   "fmt"
   "os"
   "strconv"
   "strings"

)

func main() {

   in := bufio.NewReader(os.Stdin)
   fmt.Print("Enter string: ")
   s, err := in.ReadString('\n')
   if err != nil {
       fmt.Println(err)
       return
   }
   s = strings.TrimSpace(s)
   fmt.Print("Enter 75000: ")
   s, err = in.ReadString('\n')
   if err != nil {
       fmt.Println(err)
       return
   }
   n, err := strconv.Atoi(strings.TrimSpace(s))
   if err != nil {
       fmt.Println(err)
       return
   }
   if n != 75000 {
       fmt.Println("fail:  not 75000")
       return
   }
   fmt.Println("Good")

} </lang>

Frink

<lang frink> s = input["Enter a string: "] i = parseInt[input["Enter an integer: "]] </lang>

Groovy

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

Haskell

<lang haskell>import System.IO (hFlush, stdout) main = do

   putStr "Enter a string: "
   hFlush stdout
   str <- getLine
   putStr "Enter an integer: "
   hFlush stdout
   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. Note also: Haskell doesn't automatically flush stdout when doing input, so explicit flushes are necessary.

Icon and Unicon

The following works in both Icon and Unicon:

<lang icon> procedure main ()

 writes ("Enter something: ")
 s := read ()
 write ("You entered: " || s)
 writes ("Enter 75000: ")
 if (i := integer (read ())) then 
   write (if (i = 75000) then "correct" else "incorrect")
 else write ("you must enter a number")

end </lang>

Io

<lang io>string := File clone standardInput readLine("Enter a string: ") integer := File clone standardInput readLine("Enter 75000: ") asNumber</lang>

J

Solution <lang j> require 'misc' NB. load system script

  prompt 'Enter string: '
  0".prompt 'Enter an integer: '</lang>

Example Usage <lang j> prompt 'Enter string: ' NB. output string to session Enter string: Hello World Hello World

  0".prompt 'Enter an integer: '             NB. output integer to session

Enter an integer: 75000 75000

  mystring=: prompt 'Enter string: '         NB. store string as noun

Enter string: Hello Rosetta Code

  myinteger=: 0".prompt 'Enter an integer: ' NB. store integer as noun

Enter an integer: 75000

  mystring;myinteger                         NB. show contents of nouns

┌──────────────────┬─────┐ │Hello Rosetta Code│75000│ └──────────────────┴─────┘ </lang>

Java

<lang java> import java.util.Scanner;

public class GetInput {

   public static void main(String[] args) throws Exception {
       Scanner s = new Scanner(System.in);
       System.out.print("Enter a string: ");
       String str = s.nextLine();
       System.out.print("Enter an integer: ");
       int i = Integer.parseInt(s.next());
   }

}</lang>

or

Works with: Java version 1.5/5.0+

<lang java>import java.util.Scanner;

public class GetInput {

   public static void main(String[] args) {
       Scanner stdin = new Scanner(System.in);
       String string = stdin.nextLine();
       int number = stdin.nextInt();
   }

}</lang>

JavaScript

Works with: JScript

and only with cscript.exe

<lang javascript>WScript.Echo("Enter a string"); var str = WScript.StdIn.ReadLine();

var val = 0; while (val != 75000) {

   WScript.Echo("Enter the integer 75000");
   val = parseInt( WScript.StdIn.ReadLine() );

}</lang>

Works with: SpiderMonkey

<lang javascript>print("Enter a string"); var str = readline();

var val = 0; while (val != 75000) {

   print("Enter the integer 75000");
   val = parseInt( readline() );

}</lang>

Joy

<lang Joy> "Enter a string: " putchars stdin fgets "Enter a number: " putchars stdin fgets 10 strtol. </lang>

Julia

<lang Julia> print("String? ") y = chomp(readline()) println("Your input was \"", y, "\".\n") print("Integer? ") y = chomp(readline()) try

   y = parseint(y)
   println("Your input was \"", y, "\".\n")

catch

   println("Sorry, but \"", y, "\" does not compute as an integer.")

end </lang>

Output:
String? cheese
Your input was "cheese".

Integer? 75000
Your input was "75000".

mike@harlan:~/rosetta/julia$ julia user_input_text.jl
String? theory
Your input was "theory".

Integer? 75,000
Sorry, but "75,000" does not compute as an integer.

Kite

<lang Kite> System.file.stdout|write("Enter a String "); string = System.file.stdin|readline(); </lang>


Lasso

<lang Lasso>#!/usr/bin/lasso9

define read_input(prompt::string) => {

local(string)

// display prompt stdout(#prompt) // the following bits wait until the terminal gives you back a line of input while(not #string or #string -> size == 0) => { #string = file_stdin -> readsomebytes(1024, 1000) } #string -> replace(bytes('\n'), bytes())

return #string -> asstring

}

local( string, number )

// get string

  1. string = read_input('Enter the string: ')

// get number

  1. number = integer(read_input('Enter the number: '))

// deliver the result stdoutnl(#string + ' (' + #string -> type + ') | ' + #number + ' (' + #number -> type + ')')</lang>

Output:

Enter the string: Hello
Enter the number: 1234
Hello (string) | 1234 (integer)

Liberty BASIC

<lang lb>Input "Enter a string. ";string$ Input "Enter the value 75000.";num</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>

Logtalk

Using an atom representation for strings and type-check failure-driven loops: <lang logtalk>

- object(user_input).
   :- public(test/0).
   test :-
       repeat,
           write('Enter an integer: '),
           read(Integer),
       integer(Integer),
       !,
       repeat,
           write('Enter an atom: '),
           read(Atom),
       atom(Atom),
       !.
- end_object.

</lang> Output: <lang text> | ?- user_input::test. Enter an integer: 75000. Enter an atom: 'Hello world!'. yes </lang>

Lua

<lang Lua>print('Enter a string: ') s = io.stdin:read() print('Enter a number: ') i = tonumber(io.stdin:read()) </lang>

Mathematica / Wolfram Language

<lang Mathematica>mystring = InputString["give me a string please"]; myinteger = Input["give me an integer please"];</lang>

MATLAB

The input() function automatically converts the user input to the correct data type (i.e. string or double). We can force the input to be interpreted as a string by using an optional parameter 's'.

Sample usage: <lang MATLAB>>> input('Input string: ') Input string: 'Hello'

ans =

Hello

>> input('Input number: ') Input number: 75000

ans =

      75000

>> input('Input number, the number will be stored as a string: ','s') Input number, the number will be stored as a string: 75000

ans =

75000</lang>


Metafont

<lang metafont>string s; message "write a string: "; s := readstring; message s; message "write a number now: "; b := scantokens readstring; if b = 750:

 message "You've got it!"

else:

 message "Sorry..."

fi; end</lang>

If we do not provide a number in the second input, Metafont will complain. (The number 75000 was reduced to 750 since Metafont biggest number is near 4096).

Mirah

<lang mirah>s = System.console.readLine()

puts s</lang>

mIRC Scripting Language

<lang mirc>alias askmesomething {

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

}</lang>

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>

MUMPS

<lang MUMPS>TXTINP

NEW S,N
WRITE "Enter a string: "
READ S,!
WRITE "Enter the number 75000: "
READ N,!
KILL S,N
QUIT</lang>

Nemerle

<lang Nemerle>using System; using System.Console;

module Input {

   Main() : void
   {
       Write("Enter a string:");
       _ = ReadLine()
       mutable entry = 0;
       mutable numeric = false;
       
       do
       {
           Write("Enter 75000:");
           numeric = int.TryParse(ReadLine(), out entry);
       } while ((!numeric) || (entry != 75000)) 
   }

}</lang>

NetRexx

<lang NetRexx>/* NetRexx */ options replace format comments java crossref symbols nobinary

checkVal = 75000 say 'Input a string then the number' checkVal parse ask inString parse ask inNumber .

say 'Input string:' inString say 'Input number:' inNumber if inNumber == checkVal then do

 say 'Success!  Input number is as requested'
 end

else do

 say 'Failure!  Number' inNumber 'is not' checkVal
 end

return </lang>

newLISP

Works with: newLISP version 9.0

<lang lisp>(print "Enter an integer: ") (set 'x (read-line)) (print "Enter a string: ") (set 'y (read-line))</lang>

Nim

<lang nim>import rdstdin, strutils

let str = readLineFromStdin "Input a string: " let num = parseInt(readLineFromStdin "Input a string: ")</lang>

Objeck

<lang objeck> use IO;

bundle Default {

 class Hello {
   function : Main(args : String[]) ~ Nil {
     string := Console->GetInstance()->ReadString();
     string->PrintLine();
     number := Console->GetInstance()->ReadString()->ToInt();
     number->PrintLine();
   }
 }

} </lang>

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>

Octave

<lang octave>% read a string ("s") s = input("Enter a string: ", "s");

% read a GNU Octave expression, which is evaluated; e.g. % 5/7 gives 0.71429 i = input("Enter an expression: ");

% parse the input for an integer printf("Enter an integer: "); ri = scanf("%d");

% show the values disp(s); disp(i); disp(ri);</lang>

Oforth

<lang Oforth>func: testInput { | s n |

  System.Console askln ->s
  while (System.Console askln asInteger dup ->n isNull) [ "Not an integer" println ]
  System.Out "Received : " << s << " and " << n << cr

}</lang>

Oz

<lang oz>declare

 StdIn = {New class $ from Open.file Open.text end init(name:stdin)}
 StringInput
 Num = {NewCell 0}

in

 {System.printInfo "Enter a string: "}
 StringInput = {StdIn getS($)}
 for until:@Num == 75000 do
    {System.printInfo "Enter 75000: "}
    Line = {StdIn getS($)}
 in
    Num := try {String.toInt Line} catch _ then 0 end
 end</lang>

PARI/GP

<lang parigp>s=input(); n=eval(input());</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>

Perl 6

<lang perl6>my $str = prompt("Enter a string: "); my $int = prompt("Enter a integer: ");</lang>

PHP

Works with: CLI SAPI

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

PicoLisp

<lang PicoLisp>(in NIL # Guarantee reading from standard input

  (let (Str (read)  Num (read))
     (prinl "The string is: \"" Str "\"")
     (prinl "The number is: " Num) ) )</lang>

Pike

<lang pike>int main(){

  write("Enter a String: ");
  string str = Stdio.stdin->gets();
  write("Enter 75000: ");
  int num = Stdio.stdin->gets();

}</lang>

PL/I

<lang PL/I>declare s character (100) varying; declare k fixed decimal (15);

put ('please type a string:'); get edit (s) (L); put skip list (s);

put skip list ('please type the integer 75000'); get list (k); put skip list (k); put skip list ('Thanks');</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

<lang powershell>$string = Read-Host "Input a string" [int]$number = Read-Host "Input a number"</lang>

PureBasic

<lang PureBasic>If OpenConsole()

 ; Declare a string and a integer to be used
 Define txt.s, num.i
 Print("Enter a string: ")
 txt=Input()
 Repeat
   Print("Enter the number 75000: ")
   num=Val(Input()) ; Converts the Input to a Value with Val()
 Until num=75000
 ; Check that the user really gives us 75000!
 
 Print("You made it!")
 Delay(3000): CloseConsole()

EndIf</lang>

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.

R

Works with: R version 2.81

<lang R>stringval <- readline("String: ") intval <- as.integer(readline("Integer: "))</lang>

Racket

<lang Racket>

  1. lang racket

(printf "Input a string: ") (define s (read-line)) (printf "You entered: ~a\n" s)

(printf "Input a number: ") (define m (or (string->number (read-line))

             (error "I said a number!")))

(printf "You entered: ~a\n" m)

alternatively, use the generic `read'

(printf "Input a number: ") (define n (read)) (unless (number? n) (error "I said a number!")) (printf "You entered: ~a\n" n) </lang>

Rascal

It is possible to use the eclipse IDE to create consoles. However, just as with the graphical input, this will always return a string. This string can subsequently be evaluated. A very simple example would be: <lang rascal>import util::IDE; public void InputConsole(){

   x = "";                                   
   createConsole("Input Console",                             
                 "Welcome to the Input Console\nInput\> ", 
                 str (str inp) {x = "<inp == "75000" ? "You entered 75000" : "You entered a string">";
                		 return "<x>\n<inp>\nInput\>";});

}</lang> Which has as output:

This makes it relatively easy to create Domain Specific Languages (or any programming language) and to create a rascal console for this. For examples with Exp, Func and Lisp, see the online Language Examples.

Raven

<lang raven>'Input a string: ' print expect as str 'Input an integer: ' print expect 0 prefer as num</lang>

REBOL

<lang REBOL>REBOL [ Title: "Textual User Input" Author: oofoe Date: 2009-12-07 URL: http://rosettacode.org/wiki/User_Input_-_text ]

s: n: ""

Because I have several things to check for, I've made a function to
handle it. Note the question mark in the function name, this convention
is often used in Forth to indicate test of some sort.

valid?: func [s n][ error? try [n: to-integer n] ; Ignore error if conversion fails. all [0 < length? s 75000 = n]]

I don't want to give up until I've gotten something useful, so I
loop until the user enters valid data.

while [not valid? s n][ print "Please enter a string, and the number 75000:" s: ask "string: " n: ask "number: " ]

It always pays to be polite...

print rejoin [ "Thank you. Your string was '" s "'."]</lang>

Output:

Please enter a string, and the number 75000:
string: This is a test.
number: ksldf
Please enter a string, and the number 75000:
string:
number: 75000
Please enter a string, and the number 75000:
string: Slert...
number: 75000
Thank you. Your string was 'Slert...'.

Retro

<lang Retro>: example ( "- )

 remapping off
 "Enter a string: " puts 10 accept tib tempString
 [ "Enter 75000: " puts getToken toNumber 75000 = cr ] until
 "Your string was: '%s'\n" puts
 remapping on ;</lang>

REXX

<lang rexx>/*REXX program gets a string and the number 75000 from the console. */

say 'Please enter a text string:' /*show prompt for a text string. */ parse pull userString /*get the user text and store it.*/

      do until userNumber=75000                 /*repeat until correct.*/
      say                                       /*display a blank line.*/
      say 'Please enter the number 75000'       /*show the nice prompt.*/
      parse pull userNumber                     /*get the user text.   */
      end   /*until*/                           /*now, check if it's OK*/
                                      /*stick a fork in it, we're done.*/</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}"</lang>

Scala

<lang scala>print("Enter a number: ") val i=Console.readLong // Task says to enter 75000 print("Enter a string: ") val s=Console.readLine</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>

Seed7

<lang seed7>$ include "seed7_05.s7i";

const proc: main is func

 local
   var integer: integer_input is 0;
   var string: string_input is "";
 begin
   write("Enter an integer: ");
   readln(integer_input);
   write("Enter a string: ");
   readln(string_input);
 end func;</lang>

Slate

<lang slate>print: (query: 'Enter a String: '). [| n |

 n: (Integer readFrom: (query: 'Enter an Integer: ')).
 (n is: Integer)
   ifTrue: [print: n]
   ifFalse: [inform: 'Not an integer: ' ; n printString]

] do.</lang>

Smalltalk

<lang smalltalk>'Enter a number: ' display. a := stdin nextLine asInteger.

'Enter a string: ' display. b := stdin nextLine.</lang>

SNOBOL4

<lang snobol4> output = "Enter a string:"

    str = trim(input)
    output = "Enter an integer:"
    int = trim(input)
    output = "String: " str " Integer: " int

end</lang>


Standard ML

<lang sml>print "Enter a string: "; let val str = valOf (TextIO.inputLine TextIO.stdIn) in (* note: this keeps the trailing newline *)

 print "Enter an integer: ";
 let val num = valOf (TextIO.scanStream (Int.scan StringCvt.DEC) TextIO.stdIn) in
   print (str ^ Int.toString num ^ "\n")
 end

end</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 -strict $num]} then { ...do something here...}</lang>

If the requirement is to prompt until the user enters the integer 75000, then: <lang tcl>set input 0 while {$input != 75000} {

   puts -nonewline "enter the number '75000': "
   flush stdout
   set input [gets stdin]

}</lang>

Of course, it's nicer to wrap the primitives in a procedure: <lang tcl>proc question {var message} {

   upvar 1 $var v
   puts -nonewline "$message: "
   flush stdout
   gets stdin $v

} question name "What is your name" question task "What is your quest" question doom "What is the air-speed velocity of an unladen swallow"</lang>

TI-83 BASIC

This program leaves the string in String1, and the integer in variable "i".

<lang ti83b>

 :Input "Enter a string:",Str1
 :Prompt i
 :If(i ≠ 75000): Then
 :Disp "That isn't 75000"
 :Else
 :Stop

</lang>

TI-89 BASIC

This program leaves the requested values in the global variables s and integer.

<lang ti89b>Prgm

 InputStr "Enter a string", s
 Loop
   Prompt integer
   If integer ≠ 75000 Then
     Disp "That wasn't 75000."
   Else
     Exit
   EndIf
 EndLoop

EndPrgm</lang>

Toka

<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</lang>

TUSCRIPT

<lang tuscript> $$ MODE TUSCRIPT LOOP ASK "Enter a string": str="" ASK "Enter an integer": int="" IF (int=='digits') THEN PRINT "int=",int," str=",str EXIT ELSE PRINT/ERROR int," is not an integer" CYCLE ENDIF ENDLOOP </lang> Output:

Enter a string >a
Enter an integer >a
@@@@@@@@  a is not an integer                                          @@@@@@@@
Enter a string >a
Enter an integer >1
int=1 str=a 

UNIX Shell

Works with: Bourne Shell

<lang bash>#!/bin/sh

read STRING read INTEGER</lang>

Vedit macro language

<lang vedit>Get_Input(1, "Enter a string: ")

  1. 2 = Get_Num("Enter a number: ")</lang>

Visual Basic .NET

Platform: .NET

Works with: Visual Basic .NET version 9.0+

Input an Integer

<lang vbnet>Dim i As Integer Console.WriteLine("Enter an Integer") i = Console.ReadLine()</lang>

Input an Integer With Error Handling

<lang vbnet>Dim i As Integer Dim iString As String Console.WriteLine("Enter an Integer") iString = Console.ReadLine() Try

   i = Convert.ToInt32(iString)

Catch ex As Exception

   Console.WriteLine("This is not an Integer")

End Try</lang>

Input a String

<lang vbnet>Dim i As String Console.WriteLine("Enter a String") i = Console.ReadLine()</lang>

XPL0

When the ChIn(0) intrinsic is first called, it collects characters from the keyboard until the Enter key is struck. It then returns to the XPL0 program where one character is pulled from the buffer each time ChIn(0) is called. When the Enter key (which is the same as a carriage return, $0D) is pulled, the program quits the loop. A zero byte is stored in place of the Enter key to mark the end of the string.

<lang XPL0>string 0; \use zero-terminated strings, instead of MSb terminated include c:\cxpl\codes; int I; char Name(128); \the keyboard buffer limits input to 128 characters

[Text(0, "What's your name? "); I:= 0; loop [Name(I):= ChIn(0); \buffered keyboard input

       if Name(I) = $0D\CR\ then quit;         \Carriage Return = Enter key
       I:= I+1;
       ];

Name(I):= 0; \terminate string Text(0, "Howdy "); Text(0, Name); Text(0, "! Now please enter ^"75000^": "); IntOut(0, IntIn(0)); CrLf(0); \echo the number ]</lang>

Example output:

What's your name? Loren Blaney
Howdy Loren Blaney! Now please enter "75000": 75000
75000

zkl

<lang zkl>str:=ask("Gimmie a string: "); n:=ask("Type 75000: ").toInt();</lang>

ZX Spectrum Basic

<lang basic>10 INPUT "Enter a string:"; s$ 20 INPUT "Enter a number: "; n</lang>