User input/Text: Difference between revisions
m
syntax highlighting fixup automation
m (→{{header|Joy}}) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 12:
=={{header|11l}}==
<
V number = Float(input(‘Input a number: ’))</
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B/4 version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
//Consts
.equ BUFFERSIZE, 100
Line 86:
svc 0 // trigger end of program
</syntaxhighlight>
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
{{libheader|Action! Real Math}}
<
PROC Main()
Line 113:
Print("Text: ") PrintE(sUser)
Print("Number: ") PrintRE(rUser)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/User_input_Text.png Screenshot from Atari 8-bit computer]
Line 128:
=={{header|Ada}}==
{{works with|GCC|4.1.2}}
<
Line : String (1 .. 1_000);
Last : Natural;
Line 142:
-- may raise exception Constraint_Error if value entered is not a well-formed integer
end Get_Integer;
</syntaxhighlight>
The functions above may be called as shown below
<
My_Integer : Integer := Get_Integer;</
Another:
<
procedure User_Input is
Line 164:
Ada.Text_IO.Put_Line (Integer'Image(I));
end User_Input;
</syntaxhighlight>
Unbounded IO:
<
Ada.Text_IO,
Ada.Integer_Text_IO,
Line 185:
Ada.Text_IO.Put_Line(Integer'Image(I));
end User_Input2;
</syntaxhighlight>
=={{header|ALGOL 68}}==
<
STRING s := read string;
print("Enter a number: ");
INT i := read int;
~</
=={{header|ALGOL W}}==
<
string(80) s;
integer n;
Line 202:
write( "Enter an integer> " );
read( n )
end.</
=={{header|Amazing Hopper}}==
Version: hopper-FLOW!
<syntaxhighlight lang="amazing hopper">
#include <flow.h>
Line 219:
LOCATE(5,2), PRNL( cadena, "\n ",número )
END
</syntaxhighlight>
{{out}}
<pre>
Line 230:
=={{header|APL}}==
<
int←⎕</
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
Line 387:
szMessErrDep: .asciz "Too large: overflow 32 bits.\n"
</syntaxhighlight>
=={{header|Arturo}}==
<
num: to :integer input "Enter an integer: "
print ["Got:" str "," num]</
{{out}}
Line 404:
=={{header|AutoHotkey}}==
===Windows console===
<
FileAppend, please type something`n, CONOUT$
FileReadLine, line, CONIN$, 1
Line 410:
FileAppend, please type '75000'`n, CONOUT$
FileReadLine, line, CONIN$, 1
msgbox % line</
===Input Command===
this one takes input regardless of which application has focus.
<
Input(String)
TrayTip, Input:, Type an int:
Line 436:
TrayTip, Input:, %Output%
}
}</
=={{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.
<
enter a string: hello world
ok,hello world/0
75000
ok,75000/75000</
=={{header|Axe}}==
Line 453:
Also, in the string entry, the data is a string of tokens, not a string of characters. Thankfully, the most common ASCII symbols (A-Z, 0-9, and some symbols) have the same values as their token counterparts. This means that this example will work for those symbols, but other tokens (especially multi-byte tokens) will cause problems. See [http://tibasicdev.wikidot.com/one-byte-tokens this table] of tokens and their codes for reference.
<
input→A
length(A)→L
Line 487:
If C≠7500
Disp "That isn't 7500"
End</
=={{header|BASIC}}==
Line 496:
This isn't a hard-and-fast rule -- for example, [[Chipmunk Basic]] ''never'' appends a question mark.
<
INPUT "Enter a number: ", i%</
Output ([[QBasic]]):
Line 503:
Enter a number: 1
==={{header|Applesoft BASIC}}===
<
20 INPUT "ENTER A NUMBER: "; I : I = INT(I)</
==={{header|Commodore BASIC}}===
Line 511:
Also, when a numeric variable is provided for input, the computer will make repeated attempts to obtain valid input from the user until the input can be clearly interpreted as a numeric value.
<
10 input "what is a word i should remember";a$
20 print "thank you."
Line 520:
70 print nn
80 end
</syntaxhighlight>
'''Output'''
Line 543:
==={{header|IS-BASIC}}===
<
110 INPUT PROMPT "Enter a string: ":ST$</
==={{header|QB64}}===
The use of a Long int (l&) is required as the Int variable type is only 2 bytes and even if _UNSIGNED can only hold values up to 65535. If no value is entered for either input value, it will continue to hold whatever value it did previously.
<
Print s$
Print l&
</syntaxhighlight>
==={{header|BASIC256}}===
<
do
input "Please enter 75000 : ", i
until i = 75000
print
print s, i</
==={{header|Run BASIC}}===
<
while i <> 75000
input "Please enter 75000 : "; i
wend
print
print s$; chr$(9); i</
==={{header|True BASIC}}===
{{works with|QBasic}}
<
INPUT s$
DO
Line 579:
PRINT
PRINT s$, i
END</
==={{header|Yabasic}}===
<
repeat
input "Please enter 75000 : " i
until i = 75000
print
print s$, chr$(9), i</
==={{header|Sinclair ZX81 BASIC}}===
<
20 INPUT S$
30 PRINT "YOU ENTERED: ";S$
Line 597:
60 IF N=75000 THEN STOP
70 PRINT "NO, ";
80 GOTO 40</
=={{header|Batch File}}==
<
set /p var=
echo %var% 75000</
=={{header|BBC BASIC}}==
<
INPUT "Enter a number: " number
PRINT "String = """ string$ """"
PRINT "Number = " ; number</
=={{header|Befunge}}==
This prompts for a string and pushes it to the stack a character at a time ('''~''') until end of input (-1).
<
^,_ >~:1+v
^ _@</
Numeric input is easier, using the '''&''' command.
<
^,_ & @</
=={{header|Bracmat}}==
<
= out'"Enter a string"
& get':?mystring
Line 633:
)
& out$(mystring is !mystring \nmynumber is !mynumber \n)
);</
<pre>{?} !doit
Enter a string
Line 646:
=={{header|C}}==
<
#include <stdlib.h>
Line 667:
return EXIT_SUCCESS;
}</
=={{header|C sharp|C#}}==
<
namespace C_Sharp_Console {
Line 686:
}
}
}</
=={{header|C++}}==
{{works with|g++}}
<
#include <string>
using namespace std;
Line 705:
cin >> string_input;
return 0;
}</
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
<syntaxhighlight lang
with
<syntaxhighlight 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 <code>if (!cin) // handle error</code>) after the first input, and then clear the error (with <code>cin.clear()</code>) if we want to get further input.
Line 717:
=={{header|Ceylon}}==
<
print("enter any text here");
value text = process.readLine();
Line 728:
print("That was not a number per se.");
}
}</
=={{header|Clojure}}==
<
(def scan (Scanner. *in*))
(def s (.nextLine scan))
(def n (.nextInt scan))</
=={{header|COBOL}}==
{{works with|OpenCOBOL}}
<
PROGRAM-ID. Get-Input.
Line 754:
GOBACK
.</
=={{header|Common Lisp}}==
<
(let ((s (read-line)))
(format t "You entered ~s~%" s))
Line 765:
(if (numberp n)
(format t "You entered ~d.~%" n)
(format t "That was not a number.")))</
=={{header|Crystal}}==
<
begin
Line 775:
rescue ex
puts ex
end</
Example with valid input:
Line 794:
=={{header|D}}==
<
void main() {
Line 806:
writeln("Read in '", number, "' and '", str, "'");
}</
=={{header|Dart}}==
<
main() {
Line 836:
}
</syntaxhighlight>
=={{header|Delphi}}==
<
{$APPTYPE CONSOLE}
Line 860:
Writeln('Invalid entry: ' + s);
until lIntegerValue = 75000;
end.</
=={{header|Déjà Vu}}==
<
!print\ s
!decode!utf-8 !read-line!stdin
Line 873:
/= 75000
catch value-error:
true</
=={{header|EasyLang}}==
<syntaxhighlight lang="text">write "Enter a string: "
a$ = input
print ""
Line 886:
until h = 75000
.
print a$ & " " & h</
=={{header|Elena}}==
ELENA 4.x :
<
public program()
Line 898:
var word := console.write:"Enter a String: ".readLine()
}</
=={{header|Elixir}}==
<syntaxhighlight lang="elixir">
a = IO.gets("Enter a string: ") |> String.strip
b = IO.gets("Enter an integer: ") |> String.strip |> String.to_integer
Line 908:
IO.puts "Integer = #{b}"
IO.puts "Float = #{f}"
</syntaxhighlight>
=={{header|Erlang}}==
<
{ok, [Number]} = io:fread("Enter a number: ","~d").</
Alternatively, you could use io:get_line to get a string:
<
=={{header|Euphoria}}==
<
sequence s
Line 926:
puts(1, s & '\n')
n = prompt_number("Enter a number:",{})
printf(1, "%d", n)</
=={{header|F_Sharp|F#}}==
<
let ask_for_input s =
Line 939:
ask_for_input "Input a string" |> ignore
ask_for_input "Enter the number 75000" |> ignore
0</
=={{header|Factor}}==
<
readln
"Enter a number: " write
readln string>number</
=={{header|Falcon}}==
<
str = input()
printl("Enter a number:")
n = int(input())</
=={{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 (^).
<
[0[^'0-$$9>0@>|~][\10*+]#%]d:
w;! d;!.</
=={{header|Fantom}}==
Line 963:
The 'toInt' method on an input string will throw an exception if the input is not a number.
<
class Main
{
Line 982:
}
}
</syntaxhighlight>
=={{header|Forth}}==
===Input a string===
<
PAD SWAP ACCEPT
PAD SWAP ;</
===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.
<
0. 16 INPUT$ DUP >R
>NUMBER NIP NIP
R> <> DUP 0= IF NIP THEN ;</
{{works with|GNU Forth}}
<
16 INPUT$ SNUMBER? ;</
{{works with|Win32Forth}}
<
16 INPUT$ NUMBER? NIP
DUP 0= IF NIP THEN ;</
Note that NUMBER? always leaves a double result on the stack.
Line 1,011:
{{works with|4tH}}
<
begin
refill drop bl parse-word ( a n)
Line 1,018:
drop ( --)
repeat ( n)
;</
Here is an example that puts it all together:
<
." 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 ;</
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<
integer :: i
Line 1,037:
read*, s
print*, "Enter the integer 75000"
read*, i</
=={{header|FreeBASIC}}==
<
Dim s As String
Line 1,050:
Print
Print s, i
Sleep</
Sample input/output
{{out}}
Line 1,062:
=={{header|Frink}}==
<
s = input["Enter a string: "]
i = parseInt[input["Enter an integer: "]]
</syntaxhighlight>
=={{header|Go}}==
Go has C-like Scan and Scanf functions for quick and dirty input:
<
import "fmt"
Line 1,081:
fmt.Println("wrong")
}
}</
Code below allows much more control over interaction and error checking.
<syntaxhighlight lang="go">
package main
Line 1,122:
fmt.Println("Good")
}
</syntaxhighlight>
=={{header|Groovy}}==
<
num = System.in.readLine().toInteger()</
=={{header|Haskell}}==
<
main = do
putStr "Enter a string: "
Line 1,137:
hFlush stdout
num <- readLn :: IO Int
putStrLn $ str ++ (show num)</
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.
=={{header|hexiscript}}==
<
let s scan str
print "Enter a number: "
let n scan int</
=={{header|HolyC}}==
<
s = GetStr("Enter a string: ");
Line 1,157:
Print("Your string: %s\n", s);
Print("75000: %d\n", Str2I64(n));</
=={{header|Icon}} and {{header|Unicon}}==
Line 1,163:
The following works in both Icon and Unicon:
<
procedure main ()
writes ("Enter something: ")
Line 1,174:
else write ("you must enter a number")
end
</syntaxhighlight>
=={{header|Io}}==
<
integer := File clone standardInput readLine("Enter 75000: ") asNumber</
=={{header|J}}==
'''Solution'''
<
prompt 'Enter string: '
0".prompt 'Enter an integer: '</
Note that <code>require'misc'</code> is old - efforts to optimize by loading misc utilities in a fine grained fashion mean that currently (J 805) that should be <code>require'general/misc/prompt'</code> and the older form fails with an error to call attention to this issue.
'''Example Usage'''
<
Enter string: Hello World
Hello World
Line 1,203:
│Hello Rosetta Code│75000│
└──────────────────┴─────┘
</syntaxhighlight>
=={{header|Java}}==
<
import java.util.Scanner;
Line 1,218:
int i = Integer.parseInt(s.next());
}
}</
or
{{works with|Java|1.5/5.0+}}
<
public class GetInput {
Line 1,231:
int number = stdin.nextInt();
}
}</
=={{header|JavaScript}}==
{{works with|JScript}} and only with <code>cscript.exe</code>
<
var str = WScript.StdIn.ReadLine();
Line 1,242:
WScript.Echo("Enter the integer 75000");
val = parseInt( WScript.StdIn.ReadLine() );
}</
{{works with|SpiderMonkey}}
<
var str = readline();
Line 1,252:
print("Enter the integer 75000");
val = parseInt( readline() );
}</
=={{header|Joy}}==
<syntaxhighlight lang=
"Enter a string: " putchars
stdin fgets
Line 1,272:
encountered, then the following program could be used on the assumption that
the inputs are all valid JSON.
<
null | until( . == int; "Expecting \(int)" | stderr | input);
Line 1,279:
(read_string | "I see the string: \(.)"),
(read(75000) | "I see the expected integer: \(.)")</
{{out}}
The following is a transcript showing the prompts (on stderr), responses (on stdin) and output (on stdout):
<
"Please enter a string"
1
Line 1,294:
"Expecting 75000"
75000
I see the expected integer: 75000</
=={{header|Julia}}==
{{works with|Julia|0.6}}
<syntaxhighlight lang="julia">
print("String? ")
y = readline()
Line 1,310:
println("Sorry, but \"", y, "\" does not compute as an integer.")
end
</syntaxhighlight>
{{out}}
Line 1,329:
=={{header|Kite}}==
<syntaxhighlight lang="kite">
System.file.stdout|write("Enter a String ");
string = System.file.stdin|readline();
</syntaxhighlight>
=={{header|Kotlin}}==
<
fun main(args: Array<String>) {
Line 1,345:
val number = readLine()!!.toInt()
} while (number != 75000)
}</
=={{header|Lasso}}==
<
define read_input(prompt::string) => {
Line 1,378:
// deliver the result
stdoutnl(#string + ' (' + #string -> type + ') | ' + #number + ' (' + #number -> type + ')')</
Output:
Line 1,387:
=={{header|Liberty BASIC}}==
<
Input "Enter the value 75000.";num</
=={{header|LIL}}==
<
write "Enter a string: "
set text [readline]
Line 1,402:
print $text
print $num</
=={{header|Logo}}==
Logo literals may be read from a line of input from stdin as either a list or a single word.
<
show map "number? :input ; [false true]
Line 1,412:
show :input + 123 ; 75123
make "input readword ; in: string 75000
show :input ; string 75000</
=={{header|Logtalk}}==
Using an atom representation for strings and type-check failure-driven loops:
<
:- object(user_input).
Line 1,433:
:- end_object.
</syntaxhighlight>
Output:
<
| ?- user_input::test.
Enter an integer: 75000.
Enter an atom: 'Hello world!'.
yes
</syntaxhighlight>
=={{header|LOLCODE}}==
<
I HAS A string
GIMMEH string
Line 1,451:
MAEK number A NUMBR
KTHXBYE
</syntaxhighlight>
=={{header|Lua}}==
<
s = io.stdin:read()
print('Enter a number: ')
i = tonumber(io.stdin:read())
</syntaxhighlight>
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module CheckIt {
Keyboard "75000"+chr$(13)
Line 1,471:
}
CheckIt
</syntaxhighlight>
=={{header|MACRO-10}}==
<syntaxhighlight lang="macro-10">
TITLE User Input
Line 1,565:
END GO
</syntaxhighlight>
Example output:
<pre>
Line 1,582:
=={{header|Maple}}==
<
printf("Integer: "); int_value := parse(readline());</
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
myinteger = Input["give me an integer please"];</
=={{header|MATLAB}}==
Line 1,593:
Sample usage:
<
Input string: 'Hello'
Line 1,612:
ans =
75000</
=={{header|Metafont}}==
<
message "write a string: ";
s := readstring;
Line 1,627:
message "Sorry..."
fi;
end</
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).
Line 1,633:
=={{header|min}}==
{{works with|min|0.19.3}}
<
"Enter an integer" ask int</
=={{header|Mirah}}==
<
puts s</
=={{header|mIRC Scripting Language}}==
<
echo -a You answered: $input(What's your name?, e)
}</
=={{header|Modula-3}}==
<
IMPORT IO, Fmt;
Line 1,660:
number := IO.GetInt();
IO.Put("You entered: " & string & " and " & Fmt.Int(number) & "\n");
END Input.</
=={{header|MUMPS}}==
<
NEW S,N
WRITE "Enter a string: "
Line 1,670:
READ N,!
KILL S,N
QUIT</
=={{header|Nanoquery}}==
<
integer = int(input("Enter an integer: "))</
=={{header|Neko}}==
<syntaxhighlight lang="actionscript">/**
User input/Text, in Neko
Tectonics:
Line 1,711:
if num == 75000 $print("Rosetta Code 75000, for the win!\n")
else $print("Sorry, need 75000\n")
} catch problem $print("Exception: ", problem, "\n")</
{{out}}
Line 1,723:
=={{header|Nemerle}}==
<
using System.Console;
Line 1,742:
} while ((!numeric) || (entry != 75000))
}
}</
=={{header|NetRexx}}==
<
options replace format comments java crossref symbols nobinary
Line 1,762:
end
return
</syntaxhighlight>
=={{header|newLISP}}==
{{works with|newLISP|9.0}}
<
(set 'x (read-line))
(print "Enter a string: ")
(set 'y (read-line))</
=={{header|Nim}}==
<
let str = readLineFromStdin "Input a string: "
let num = parseInt(readLineFromStdin "Input an integer: ")</
=={{header|NS-HUBASIC}}==
<
20 PRINT "YOU ENTERED ";STRING$;"."
30 INPUT "ENTER AN INTEGER: ",INTEGER
40 PRINT "YOU ENTERED";INTEGER;"."</
=={{header|Oberon-2}}==
{{works with|oo2c}}
<
MODULE InputText;
IMPORT
Line 1,797:
Out.String("Enter a string: ");Out.Flush();In.String(str);
END InputText.
</syntaxhighlight>
=={{header|Objeck}}==
<
use IO;
Line 1,814:
}
}
</syntaxhighlight>
=={{header|OCaml}}==
<
let str = read_line () in
print_string "Enter an integer: ";
let num = read_int () in
Printf.printf "%s%d\n" str num</
=={{header|Octave}}==
<
s = input("Enter a string: ", "s");
Line 1,839:
disp(s);
disp(i);
disp(ri);</
=={{header|Oforth}}==
<
: testInput{
Line 1,850:
while (System.Console askln asInteger dup ->n isNull) [ "Not an integer" println ]
System.Out "Received : " << s << " and " << n << cr ;</
=={{header|Oz}}==
<
StdIn = {New class $ from Open.file Open.text end init(name:stdin)}
StringInput
Line 1,866:
in
Num := try {String.toInt Line} catch _ then 0 end
end</
=={{header|PARI/GP}}==
<
n=eval(input());</
=={{header|Pascal}}==
<
var i : Integer;
s : String;
Line 1,882:
write('Enter a string: ');
readln(s)
end.</
=={{header|Perl}}==
<
my $string = <>;
print "Enter an integer: ";
my $integer = <>;</
=={{header|Phix}}==
<!--<
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">prompt_string</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Enter any string:"</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">prompt_number</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Enter the number 75000:"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">75000</span><span style="color: #0000FF;">,</span><span style="color: #000000;">75000</span><span style="color: #0000FF;">})</span>
<!--</
{{out}}
<pre>
Line 1,907:
=={{header|PHP}}==
{{works with|CLI SAPI}}
<
<?php
$string = fgets(STDIN);
$integer = (int) fgets(STDIN);</
=={{header|Picat}}==
<
print("Enter a string: "),
String = read_line(),
print("Enter a number: "),
Number = read_int(),
println([string=String,number=Number]).</
=={{header|PicoLisp}}==
<
(let (Str (read) Num (read))
(prinl "The string is: \"" Str "\"")
(prinl "The number is: " Num) ) )</
=={{header|Pike}}==
<
write("Enter a String: ");
string str = Stdio.stdin->gets();
write("Enter 75000: ");
int num = Stdio.stdin->gets();
}</
=={{header|PL/I}}==
<
declare k fixed decimal (15);
Line 1,945:
get list (k);
put skip list (k);
put skip list ('Thanks');</
=={{header|Plain English}}==
<
Start up.
Demonstrate input.
Line 1,961:
\Now show the input values
Write "The string: " then the string to the console.
Write "The number: " then the number to the console.</
A sample run of the program:
{{out}}
Line 1,972:
=={{header|Pop11}}==
<
lvars itemrep = incharitem(charin);
lvars s, c, j = 0;
Line 1,980:
consstring(j) -> s;
;;; read the integer
lvars i = itemrep();</
=={{header|PostScript}}==
{{works with|PostScript|level-2}}
<
/kbd (%stdin) (r) file def
%make ten-char buffer to read string into:
/buf (..........) def
%read string into buffer:
kbd buf readline</
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:
<
{cvi} if</
which will read the conversion operator 'cvi' (convert to integer) and the boolean and execute the former if the latter is true.
Line 2,000:
=={{header|PowerShell}}==
<
[int]$number = Read-Host "Input a number"</
=={{header|PureBasic}}==
<
; Declare a string and a integer to be used
Define txt.s, num.i
Line 2,020:
Print("You made it!")
Delay(3000): CloseConsole()
EndIf</
=={{header|Python}}==
===Input a string===
<
In Python 3.0, raw_input will be renamed to input(). The Python 3.0 equivalent would be
<
===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.
<
Python 3.0 equivalent:
<
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.
<
Python 3.0 equivalent:
<
float may be replaced by any numeric type, such as int, complex, or decimal.Decimal. Each one varies in expected input.
Line 2,042:
The word <code>$->n</code> attempts to convert a string to an integer, and returns an integer and a success flag. Validating the input is not part of the task, but since the flag is there we might as well use it. Similarly, might as well trim leading and trailing spaces, because ''users'', eh.
<
say 'You entered: "' echo$ say '"' cr cr
Line 2,051:
else
[ say "That was not an integer." cr
drop ]</
{{out}}
Line 2,065:
{{works with|R|2.81}}
<
intval <- as.integer(readline("Integer: "))</
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
(printf "Input a string: ")
Line 2,086:
(unless (number? n) (error "I said a number!"))
(printf "You entered: ~a\n" n)
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
my $int = prompt("Enter a integer: ");</
=={{header|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:
<
public void InputConsole(){
x = "";
Line 2,102:
str (str inp) {x = "<inp == "75000" ? "You entered 75000" : "You entered a string">";
return "<x>\n<inp>\nInput\>";});
}</
Which has as output:
Line 2,110:
=={{header|Raven}}==
<
'Input an integer: ' print expect 0 prefer as num</
=={{header|REBOL}}==
<
Title: "Textual User Input"
URL: http://rosettacode.org/wiki/User_Input_-_text
Line 2,140:
; It always pays to be polite...
print rejoin [ "Thank you. Your string was '" s "'."]</
Output:
Line 2,156:
=={{header|Red}}==
<
=={{header|Retro}}==
<
'Enter_a_string:_ s:put s:get s:keep
[ 'Enter_75000:_ s:put s:get-word s:to-number nl #75000 eq? ] until
'Your_string_was:_'%s'\n s:format s:put ;</
=={{header|REXX}}==
Line 2,177:
do until userNumber==75000
<
say 'Please enter a string:' /*issue a prompt message to the term. */
parse pull userString /*the (char) string can be any length. */
Line 2,186:
parse pull userNumber /*obtain the user text from terminal. */
end /*until*/ /*check if the response is legitimate. */
/*stick a fork in it, we're all done. */</
=={{header|Ring}}==
<
see "Enter a string : " give s
see "Enter an integer : " give i
see "String = " + s + nl
see "Integer = " + i + nl
</syntaxhighlight>
=={{header|Robotic}}==
<
input string "Enter string:"
set "$str" to "input"
Line 2,206:
[ "&number&"
end
</syntaxhighlight>
To ensure that a specific number must be entered, just create a loop around the second input function:
<
input string "Enter string:"
set "$str" to "input"
Line 2,220:
[ "&number&"
end
</syntaxhighlight>
=={{header|Ruby}}==
{{works with|Ruby|1.8.4}}
<
s = gets
printf "Enter an integer: "
Line 2,232:
puts "String = #{s}"
puts "Integer = #{i}"
puts "Float = #{f}"</
=={{header|Rust}}==
This program shows all the proper error handling.
<
use std::fmt::Display;
use std::process;
Line 2,267:
let _ = writeln!(&mut io::stderr(), "Error: {}", msg);
process::exit(code)
}</
=={{header|Scala}}==
<
val i=Console.readLong // Task says to enter 75000
print("Enter a string: ")
val s=Console.readLine</
=={{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>
<
(define num (read))
(display "String = ") (display str)
(display "Integer = ") (display num)</
=={{header|Seed7}}==
<
const proc: main is func
Line 2,294:
write("Enter a string: ");
readln(string_input);
end func;</
=={{header|Sidef}}==
Using the '''read(Type)''' built-in function:
<
var i = read(Number); # auto-conversion to a number</
or using the '''Sys.readln(msg)''' method:
<
var i = Sys.readln("Enter a number: ").to_i;</
=={{header|Slate}}==
<
[| n |
n: (Integer readFrom: (query: 'Enter an Integer: ')).
Line 2,312:
ifTrue: [print: n]
ifFalse: [inform: 'Not an integer: ' ; n printString]
] do.</
=={{header|Smalltalk}}==
<
a := stdin nextLine asInteger.
'Enter a string: ' display.
b := stdin nextLine.</
=={{header|smart BASIC}}==
Line 2,325:
'''NOTE:''' The INPUT command uses a colon (:) as opposed to a comma (,) or semi-conlon (;) like other forms of BASIC.
<
INPUT "Enter the value 75000.":n</
=={{header|SNOBOL4}}==
<
str = trim(input)
output = "Enter an integer:"
int = trim(input)
output = "String: " str " Integer: " int
end</
=={{header|SPL}}==
In SPL all console input is text, so number should be converted from text using #.val function.
<
number = #.val(#.input("Input a number"))</
=={{header|Standard ML}}==
<
let val str = valOf (TextIO.inputLine TextIO.stdIn) in (* note: this keeps the trailing newline *)
print "Enter an integer: ";
Line 2,348:
print (str ^ Int.toString num ^ "\n")
end
end</
=={{header|Swift}}==
{{works with|Swift|2.x+}}
<
if let str = readLine() {
print(str)
}</
{{works with|Swift|5.x+}}
<
guard let str = readLine() else {
fatalError("Nothing read!")
Line 2,366:
fatalError("Not a number!")
}
print(num)</
=={{header|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:
<
set num [gets stdin]</
possibly followed by something like
<
If the requirement is to prompt until the user enters the integer 75000, then:
<
while {$input != 75000} {
puts -nonewline "enter the number '75000': "
flush stdout
set input [gets stdin]
}</
Of course, it's nicer to wrap the primitives in a procedure:
<
upvar 1 $var v
puts -nonewline "$message: "
Line 2,392:
question name "What is your name"
question task "What is your quest"
question doom "What is the air-speed velocity of an unladen swallow"</
=={{header|TI-83 BASIC}}==
Line 2,398:
This program leaves the string in String1, and the integer in variable "i".
<
:Input "Enter a string:",Str1
:Prompt i
Line 2,405:
:Else
:Stop
</syntaxhighlight>
=={{header|TI-89 BASIC}}==
Line 2,411:
This program leaves the requested values in the global variables ''s'' and ''integer''.
<
InputStr "Enter a string", s
Loop
Line 2,421:
EndIf
EndLoop
EndPrgm</
=={{header|Toka}}==
<
." 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</
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT
LOOP
Line 2,445:
ENDIF
ENDLOOP
</syntaxhighlight>
Output:
<pre>
Line 2,458:
=={{header|UNIX Shell}}==
{{works with|Bourne Shell}}
<
read string
read integer
read -p 'Enter a number: ' number
echo "The number is $number"</
=={{header|Ursa}}==
<
# user input
#
Line 2,479:
set i (in int console)
out "you entered " str " and " i endl console</
=={{header|VBA}}==
<
Debug.Print InputBox("Input a string")
Debug.Print InputBox("Input the integer 75000", "Input an integer", 75000, Context = "Long")
End Sub</
=={{header|Vedit macro language}}==
<
#2 = Get_Num("Enter a number: ")</
=={{header|Visual Basic .NET}}==
Line 2,497:
===Input an Integer===
<
Console.WriteLine("Enter an Integer")
i = Console.ReadLine()</
===Input an Integer With Error Handling===
<
Dim iString As String
Console.WriteLine("Enter an Integer")
Line 2,510:
Catch ex As Exception
Console.WriteLine("This is not an Integer")
End Try</
===Input a String===
<
Console.WriteLine("Enter a String")
i = Console.ReadLine()</
=={{header|Vlang}}==
<
fn main() {
Line 2,527:
println('bad')
}
}</
==Input conversion with Error Handling==
<syntaxhighlight lang="text">import os
import strconv
Line 2,540:
println('bad $s')
}
}</
=={{header|Wee Basic}}==
<syntaxhighlight lang="text">print 1 "Enter a string."
input string$
print 1 "Enter an integer."
input integer</
=={{header|Wren}}==
<
var string
Line 2,577:
System.print("\nYou entered:")
System.print(" string: %(string)")
System.print(" number: %(number)")</
{{out}}
Line 2,591:
=={{header|XLISP}}==
<tt>READ-LINE</tt> reads a line of input as a string; <tt>READ</tt> reads an expression, of arbitrary complexity.
<
(define s (read-line))
(display "Yes, ")
Line 2,606:
"That is not the integer 75000." )
(t
"Yes, that is the integer 75000." ) ) )</
{{out}}
<pre>Enter a string: Rosetta Code
Line 2,621:
place of the Enter key to mark the end of the string.
<
include c:\cxpl\codes;
int I;
Line 2,635:
Text(0, "Howdy "); Text(0, Name); Text(0, "! Now please enter ^"75000^": ");
IntOut(0, IntIn(0)); CrLf(0); \echo the number
]</
Example output:
Line 2,645:
=={{header|zkl}}==
<
n:=ask("Type 75000: ").toInt();</
=={{header|ZX Spectrum Basic}}==
<
20 INPUT "Enter a number: "; n</
{{omit from|GUISS|We need an application that asks for these}}
|