User input/Text: Difference between revisions

From Rosetta Code
Content added Content deleted
m (→‎{{header|JavaScript}}: spidermonkey's javascript implementation has print/readline)
m (Fixed lang tags.)
Line 4: Line 4:
=={{header|Ada}}==
=={{header|Ada}}==
{{works with|GCC|4.1.2}}
{{works with|GCC|4.1.2}}
<lang ada>
<lang ada>function Get_String return String is
Line : String (1 .. 1_000);
function Get_String return String is
Last : Natural;
Line : String (1 .. 1_000);
begin
Last : Natural;
Get_Line (Line, Last);
begin
Get_Line (Line, Last);
return Line (1 .. Last);
end Get_String;
return Line (1 .. Last);
function Get_Integer return Integer is
end Get_String;
S : constant String := Get_String;
function Get_Integer return Integer is
begin
S : constant String := Get_String;
return Integer'Value (S);
begin
-- may raise exception Constraint_Error if value entered is not a well-formed integer
return Integer'Value (S);
end Get_Integer;</lang>
-- 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
The functions above may be called as shown below
<lang ada>
<lang ada>My_String : String := Get_String;
My_Integer : Integer := Get_Integer;</lang>
My_String : String := Get_String;
My_Integer : Integer := Get_Integer;
</lang>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
print("Enter a string: ");
<lang algol68>print("Enter a string: ");
STRING s := read string;
STRING s := read string;
print("Enter a number: ");
print("Enter a number: ");
INT i := read int;
INT i := read int;
~</lang>
~
=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
===Windows console===
===Windows console===
<lang AutoHotkey>
<lang AutoHotkey>DllCall("AllocConsole")
DllCall("AllocConsole")
FileAppend, please type something`n, CONOUT$
FileAppend, please type something`n, CONOUT$
FileReadLine, line, CONIN$, 1
FileReadLine, line, CONIN$, 1
Line 70: Line 65:
=={{header|AWK}}==
=={{header|AWK}}==
This demo shows a same-line prompt, and that the integer i becomes 0 if the line did not parse as an integer.
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}'
<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
enter a string: hello world
ok,hello world/0
ok,hello world/0
75000
75000
ok,75000/75000
ok,75000/75000</lang>
</lang>


=={{header|BASIC}}==
=={{header|BASIC}}==
Line 92: Line 85:
=={{header|Befunge}}==
=={{header|Befunge}}==
This prompts for a string and pushes it to the stack a character at a time ('''~''') until end of input (-1).
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: "
<lang befunge><>:v:"Enter a string: "
^,_ >~:1+v
^,_ >~:1+v
^ _@
^ _@</lang>


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


=={{header|C}}==
=={{header|C}}==
{{works with|gcc}}
{{works with|gcc}}
<lang c> #include <stdio.h>
<lang c>#include <stdio.h>
int main(int argc, char* argv[])
int main(int argc, char* argv[])
{
{
int input;
int input;
if((scanf("%d", &input))==1)
if((scanf("%d", &input))==1)
{
{
printf("Read in %d\n", input);
printf("Read in %d\n", input);
return 1;
return 1;
}
}
return 0;
return 0;
}</lang>
}</lang>


=={{header|C++}}==
=={{header|C++}}==
{{works with|g++}}
{{works with|g++}}
<lang cpp> #include <iostream>
<lang cpp>#include <iostream>
#include <string>
#include <string>
using namespace std;
using namespace std;

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


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp> using System;
<lang csharp>using System;

namespace C_Sharp_Console {
namespace C_Sharp_Console {

class example {
class example {

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


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>(import '(java.util Scanner))
<lang lisp>(import '(java.util Scanner))
(def scan (Scanner. *in*))
(def scan (Scanner. *in*))
(def s (.nextLine scan))
(def s (.nextLine scan))
(def n (.nextInt scan))
(def n (.nextInt scan))</lang>
</lang>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Line 194: Line 186:


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang> {ok, [String]} = io:fread("Enter a string: ","~s").
<lang erlang>{ok, [String]} = io:fread("Enter a string: ","~s").
{ok, [Number]} = io:fread("Enter a number: ","~d").</lang>
{ok, [Number]} = io:fread("Enter a number: ","~d").</lang>


Alternatively, you could use io:get_line to get a string:
Alternatively, you could use io:get_line to get a string:
Line 202: Line 194:
=={{header|FALSE}}==
=={{header|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 (^).
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 (^).
[[^$' =~][,]#,]w:
<lang false>[[^$' =~][,]#,]w:
[0[^'0-$$9>0@>|~][\10*+]#%]d:
[0[^'0-$$9>0@>|~][\10*+]#%]d:
w;! d;!.
w;! d;!.</lang>


=={{header|Forth}}==
=={{header|Forth}}==
===Input a string===
===Input a string===


<lang forth> : INPUT$ ( n -- addr n )
<lang forth>: INPUT$ ( n -- addr n )
PAD SWAP ACCEPT
PAD SWAP ACCEPT
PAD SWAP ;</lang>
PAD SWAP ;</lang>


===Input a number===
===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.
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 )
<lang forth>: INPUT# ( -- u true | false )
0. 16 INPUT$ DUP >R
0. 16 INPUT$ DUP >R
>NUMBER NIP NIP
>NUMBER NIP NIP
R> <> DUP 0= IF NIP THEN ;</lang>
R> <> DUP 0= IF NIP THEN ;</lang>


{{works with|GNU Forth}}
{{works with|GNU Forth}}
<lang forth> : INPUT# ( -- n true | d 1 | false )
<lang forth>: INPUT# ( -- n true | d 1 | false )
16 INPUT$ SNUMBER? ;</lang>
16 INPUT$ SNUMBER? ;</lang>


{{works with|Win32Forth}}
{{works with|Win32Forth}}
<lang forth> : INPUT# ( -- n true | false )
<lang forth>: INPUT# ( -- n true | false )
16 INPUT$ NUMBER? NIP
16 INPUT$ NUMBER? NIP
DUP 0= IF NIP THEN ;</lang>
DUP 0= IF NIP THEN ;</lang>


Note that NUMBER? always leaves a double result on the stack.
Note that NUMBER? always leaves a double result on the stack.
Line 234: Line 226:
Here is an example that puts it all together:
Here is an example that puts it all together:


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


=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
{{works with|Fortran|90 and later}}
<lang fortran>
<lang fortran>character(20) :: s
character(20) :: s
integer :: i
integer :: i


Line 250: Line 241:
read*, s
read*, s
print*, "Enter the integer 75000"
print*, "Enter the integer 75000"
read*, i
read*, i</lang>
</lang>


=={{header|Groovy}}==
=={{header|Groovy}}==
<lang groovy> word = System.in.readLine()
<lang groovy>word = System.in.readLine()
num = System.in.readLine().toInteger()</lang>
num = System.in.readLine().toInteger()</lang>


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>
<lang haskell>import System.IO (hFlush, stdout)
main = do
import System.IO (hFlush, stdout)
putStr "Enter a string: "
main = do
hFlush stdout
putStr "Enter a string: "
hFlush stdout
str <- getLine
str <- getLine
putStr "Enter an integer: "
hFlush stdout
putStr "Enter an integer: "
num <- readLn :: IO Int
hFlush stdout
putStrLn $ str ++ (show num)</lang>
num <- readLn :: IO Int
putStrLn $ str ++ (show num)</lang>
Note: <tt>:: IO Int</tt> is only there to disambiguate what type we wanted from <tt>read</tt>. If <tt>num</tt> were used in a numerical context, its type would have been inferred by the interpreter/compiler.
Note: <tt>:: IO Int</tt> is only there to disambiguate what type we wanted from <tt>read</tt>. If <tt>num</tt> 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.
Note also: Haskell doesn't automatically flush stdout when doing input, so explicit flushes are necessary.


=={{header|J}}==
=={{header|J}}==
<lang j>require 'misc' NB. load system script</lang>
<lang j>
<lang j>prompt 'Enter string: '
require 'misc' NB. load system script
</lang>
<lang j>
prompt 'Enter string: '


0".prompt 'Enter 75000: '
0".prompt 'Enter 75000: '</lang>
</lang>
Both of these sentences return the user provided input. But this implementation implements no error checking: For example, if a different number is entered at the second prompt, it will be used instead of 75000.
Both of these sentences return the user provided input. But this implementation implements no error checking: For example, if a different number is entered at the second prompt, it will be used instead of 75000.


=={{header|Java}}==
=={{header|Java}}==
<lang java> import java.io.BufferedReader;
<lang java>import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStreamReader;

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


or
or


{{works with|Java|1.5/5.0+}}
{{works with|Java|1.5/5.0+}}
<lang java> import java.util.Scanner;
<lang java>import java.util.Scanner;

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


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Line 326: Line 311:
=={{header|Logo}}==
=={{header|Logo}}==
Logo literals may be read from a line of input from stdin as either a list or a single word.
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
<lang logo>make "input readlist ; in: string 75000
show map "number? :input ; [false true]
show map "number? :input ; [false true]

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


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


=={{header|Metafont}}==
=={{header|Metafont}}==
Line 358: Line 341:


=={{header|mIRC Scripting Language}}==
=={{header|mIRC Scripting Language}}==
alias askmesomething {
<lang mirc>alias askmesomething {
echo -a You answered: $input(What's your name?, e)
echo -a You answered: $input(What's your name?, e)
}</lang>
}


=={{header|Modula-3}}==
=={{header|Modula-3}}==
Line 376: Line 359:
number := IO.GetInt();
number := IO.GetInt();
IO.Put("You entered: " & string & " and " & Fmt.Int(number) & "\n");
IO.Put("You entered: " & string & " and " & Fmt.Int(number) & "\n");
END Input.
END Input.</lang>
</lang>


=={{header|newLISP}}==
=={{header|newLISP}}==
{{works with|newLISP|9.0}}
{{works with|newLISP|9.0}}
(print "Enter an integer: ")
<lang lisp>(print "Enter an integer: ")
(set 'x (read-line))
(set 'x (read-line))
(print "Enter a string: ")
(print "Enter a string: ")
(set 'y (read-line))
(set 'y (read-line))</lang>


=={{header|OCaml}}==
=={{header|OCaml}}==
Line 414: Line 396:
=={{header|Pascal}}==
=={{header|Pascal}}==


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


=={{header|Perl}}==
=={{header|Perl}}==
{{works with|Perl|5.8.8}}
{{works with|Perl|5.8.8}}
<lang perl> #!/usr/bin/perl
<lang perl>#!/usr/bin/perl

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


=={{header|PHP}}==
=={{header|PHP}}==
{{works with|CLI SAPI}}
{{works with|CLI SAPI}}
<lang php> #!/usr/bin/php
<lang php>#!/usr/bin/php
<?php
<?php
$string = fgets(STDIN);
$string = fgets(STDIN);
$integer = (int) fgets(STDIN);</lang>
$integer = (int) fgets(STDIN);</lang>


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


=={{header|PostScript}}==
=={{header|PostScript}}==
{{works with|PostScript|level-2}}
{{works with|PostScript|level-2}}
<lang postscript> %open stdin for reading (and name the channel "kbd"):
<lang postscript>%open stdin for reading (and name the channel "kbd"):
/kbd (%stdin) (r) file def
/kbd (%stdin) (r) file def
%make ten-char buffer to read string into:
%make ten-char buffer to read string into:
/buf (..........) def
/buf (..........) def
%read string into buffer:
%read string into buffer:
kbd buf readline</lang>
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:
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:
<lang postscript>%if the read was successful, convert the string to integer:
{cvi} if</lang>
{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.
which will read the conversion operator 'cvi' (convert to integer) and the boolean and execute the former if the latter is true.
Line 467: Line 449:
=={{header|PowerShell}}==
=={{header|PowerShell}}==


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


=={{header|Python}}==
=={{header|Python}}==
Line 489: Line 471:
{{works with|R|2.81}}
{{works with|R|2.81}}


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


=={{header|Raven}}==
=={{header|Raven}}==
<lang raven> 'Input a string: ' print expect as str
<lang raven>'Input a string: ' print expect as str
'Input an integer: ' print expect 0 prefer as num</lang>
'Input an integer: ' print expect 0 prefer as num</lang>


=={{header|REXX}}==
=={{header|REXX}}==
Line 506: Line 486:
=={{header|Ruby}}==
=={{header|Ruby}}==
{{works with|Ruby|1.8.4}}
{{works with|Ruby|1.8.4}}
<lang ruby> print "Enter a string: "
<lang ruby>print "Enter a string: "
s = gets
s = gets
print "Enter an integer: "
print "Enter an integer: "
i = gets.to_i # If string entered, will return zero
i = gets.to_i # If string entered, will return zero
puts "String = " + s
puts "String = " + s
puts "Integer = " + i.to_s</lang>
puts "Integer = " + i.to_s</lang>


=={{header|Scheme}}==
=={{header|Scheme}}==
The <tt>read</tt> procedure is R5RS standard, inputs a scheme representation so, in order to read a string, one must enter <tt>"hello world"</tt>
The <tt>read</tt> procedure is R5RS standard, inputs a scheme representation so, in order to read a string, one must enter <tt>"hello world"</tt>
<lang scheme> (define str (read))
<lang scheme>(define str (read))
(define num (read))
(define num (read))
(display "String = ") (display str)
(display "String = ") (display str)
(display "Integer = ") (display num)</lang>
(display "Integer = ") (display num)</lang>


=={{header|Slate}}==
=={{header|Slate}}==
<lang slate>
<lang slate>print: (query: 'Enter a String: ').
print: (query: 'Enter a String: ').
[| n |
[| n |
n: (Integer readFrom: (query: 'Enter an Integer: ')).
n: (Integer readFrom: (query: 'Enter an Integer: ')).
Line 528: Line 507:
ifTrue: [print: n]
ifTrue: [print: n]
ifFalse: [inform: 'Not an integer: ' ; n printString]
ifFalse: [inform: 'Not an integer: ' ; n printString]
] do.
] do.</lang>
</lang>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
Line 580: Line 558:
This program leaves the requested values in the global variables ''s'' and ''integer''.
This program leaves the requested values in the global variables ''s'' and ''integer''.


<lang ti89b>Prgm
<pre style="font-family:'TI Uni'">Prgm
InputStr "Enter a string", s
InputStr "Enter a string", s
Loop
Loop
Line 590: Line 568:
EndIf
EndIf
EndLoop
EndLoop
EndPrgm</pre>
EndPrgm</lang>


=={{header|Toka}}==
=={{header|Toka}}==
needs readline
<lang toka>needs readline
." Enter a string: " readline is-data the-string
." Enter a string: " readline is-data the-string
." Enter a number: " readline >number [ ." Not a number!" drop 0 ] ifFalse is-data the-number
." Enter a number: " readline >number [ ." Not a number!" drop 0 ] ifFalse is-data the-number


the-string type cr
the-string type cr
the-number . cr
the-number . cr</lang>


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
{{works with|Debian Almquish SHell}}
{{works with|Debian Almquish SHell}}
#!/bin/sh
<lang bash>#!/bin/sh

read STRING
read STRING
read INTEGER
read INTEGER</lang>
{{works with|Bourne Again SHell}}
{{works with|Bourne Again SHell}}
#!/bin/bash
<lang bash>#!/bin/bash

read STRING
read STRING
read INTEGER
read INTEGER</lang>


=={{header|Vedit macro language}}==
=={{header|Vedit macro language}}==
Get_Input(1, "Enter a string: ")
<lang vedit>Get_Input(1, "Enter a string: ")
#2 = Get_Num("Enter a number: ")
#2 = Get_Num("Enter a number: ")</lang>


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==

Revision as of 16:22, 22 November 2009

Task
User input/Text
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 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>

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

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). <lang befunge><>:v:"Enter a string: "

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

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

^,_ & @</lang>

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>

  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>

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

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>

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>

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>

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.

J

<lang j>require 'misc' NB. load system script</lang> <lang j>prompt 'Enter string: '

0".prompt 'Enter 75000: '</lang> Both of these sentences return the user provided input. But this implementation implements no error checking: For example, if a different number is entered at the second prompt, it will be used instead of 75000.

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>

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>

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>

Mathematica

<lang Mathematica>mystring = InputString["give me a string please"]; myinteger = Input["give me an integer please"];</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).

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>

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>

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>


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

<lang powershell>$string = Read-Host "Input a string" $number = Read-Host "Input a number"</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>

Raven

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

REXX

<lang rexx>do until i = 75000

 say "Input 75000"
 pull i

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

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>

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

UNIX Shell

<lang bash>#!/bin/sh

read STRING read INTEGER</lang>

Works with: Bourne Again SHell

<lang bash>#!/bin/bash

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>