User input/Text
From Rosetta Code
You are encouraged to solve this task according to the task description, using any language you may know.
See also: User Input - graphical
[edit] Ada
Works with: GCC version 4.1.2
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;
The functions above may be called as shown below
My_String : String := Get_String;
My_Integer : Integer := Get_Integer;
[edit] ALGOL 68
print("Enter a string: ");
STRING s := read string;
print("Enter a number: ");
INT i := read int;
~
[edit] AutoHotkey
[edit] Windows console
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
[edit] Input Command
this one takes input regardless of which application has focus.
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%
}
}
[edit] AWK
This demo shows a same-line prompt, and that the integer i becomes 0 if the line did not parse as an integer.
~/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
[edit] 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
[edit] Befunge
This prompts for a string and pushes it to the stack a character at a time (~) until end of input (-1).
<>:v:"Enter a string: "
^,_ >~:1+v
^ _@
Numeric input is easier, using the & command.
<>:v:"Enter a number: "
^,_ & @
[edit] C
Works with: gcc
#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;
}
[edit] C++
Works with: g++
#include <iostream>
#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;
}
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
cin >> string_input;
with
getline(cin, string_input);
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.
[edit] C#
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();
}
}
}
[edit] Clojure
(import '(java.util Scanner))
(def scan (Scanner. *in*))
(def s (.nextLine scan))
(def n (.nextInt scan))
[edit] Common 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.")))
[edit] 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();
}
[edit] Erlang
{ok, [String]} = io:fread("Enter a string: ","~s").
{ok, [Number]} = io:fread("Enter a number: ","~d").
Alternatively, you could use io:get_line to get a string:
String = io:get_line("Enter a string: ").
[edit] Factor
"Enter a string: " write
readln
"Enter a number: " write
readln string>number
[edit] 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 (^).
[[^$' =~][,]#,]w:
[0[^'0-$$9>0@>|~][\10*+]#%]d:
w;! d;!.
[edit] Forth
[edit] Input a string
: INPUT$ ( n -- addr n )
PAD SWAP ACCEPT
PAD SWAP ;
[edit] 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.
: INPUT# ( -- u true | false )
0. 16 INPUT$ DUP >R
>NUMBER NIP NIP
R> <> DUP 0= IF NIP THEN ;
Works with: GNU Forth
: INPUT# ( -- n true | d 1 | false )
16 INPUT$ SNUMBER? ;
Works with: Win32Forth
: INPUT# ( -- n true | false )
16 INPUT$ NUMBER? NIP
DUP 0= IF NIP THEN ;
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
: input#
begin
refill drop bl parse-word ( a n)
number error? ( n f)
while ( n)
drop ( --)
repeat ( n)
;
Here is an example that puts it all together:
: 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 ;
[edit] Fortran
Works with: Fortran version 90 and later
character(20) :: s
integer :: i
print*, "Enter a string (max 20 characters)"
read*, s
print*, "Enter the integer 75000"
read*, i
[edit] Groovy
word = System.in.readLine()
num = System.in.readLine().toInteger()
[edit] 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)
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.
[edit] Io
string := File clone standardInput readLine("Enter a string: ")
integer := File clone standardInput readLine("Enter 75000: ") asNumber
[edit] J
Solution
require 'misc' NB. load system script
prompt 'Enter string: '
0".prompt 'Enter an integer: '
Example Usage
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│
└──────────────────┴─────┘
[edit] 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();
}
}
or
Works with: Java version 1.5/5.0+
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();
}
}
[edit] JavaScript
Works with: JScript and only with cscript.exe
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() );
}
Works with: SpiderMonkey
print("Enter a string");
var str = readline();
var val = 0;
while (val != 75000) {
print("Enter the integer 75000");
val = parseInt( readline() );
}
[edit] Liberty BASIC
Input "Enter a string. ";string$
Input "Enter the value 75000.";num
[edit] Logo
Logo literals may be read from a line of input from stdin as either a list or a single word.
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
[edit] Lua
print('Enter a string: ')
s = io.stdin:read()
print('Enter a number: ')
i = tonumber(io.stdin:read())
[edit] Mathematica
mystring = InputString["give me a string please"];
myinteger = Input["give me an integer please"];
[edit] 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:
>> 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
[edit] 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
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).
[edit] mIRC Scripting Language
alias askmesomething {
echo -a You answered: $input(What's your name?, e)
}
[edit] Modula-3
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.
[edit] MUMPS
TXTINP
NEW S,N
WRITE "Enter a string: "
READ S,!
WRITE "Enter the number 75000: "
READ N,!
KILL S,N
QUIT
[edit] newLISP
Works with: newLISP version 9.0
(print "Enter an integer: ")
(set 'x (read-line))
(print "Enter a string: ")
(set 'y (read-line))
[edit] 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
[edit] 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);
[edit] 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
[edit] Pascal
program UserInput(input, output);
var i : Integer;
s : String;
begin
write('Enter an integer: ');
readln(i);
write('Enter a string: ');
readln(s)
end.
[edit] Perl
Works with: Perl version 5.8.8
#!/usr/bin/perl
my $string = <>; # equivalent to readline(*STDIN)
my $integer = <>;
[edit] PHP
Works with: CLI SAPI
#!/usr/bin/php
<?php
$string = fgets(STDIN);
$integer = (int) fgets(STDIN);
[edit] PicoLisp
(in NIL # Guarantee reading from standard input
(let (Str (read) Num (read))
(prinl "The string is: \"" Str "\"")
(prinl "The number is: " Num) ) )
[edit] Pike
int main(){
write("Enter a String: ");
string str = Stdio.stdin->gets();
write("Enter 75000: ");
int num = Stdio.stdin->gets();
}
[edit] 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 ist ('Thanks');
[edit] 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();
[edit] PostScript
Works with: PostScript version level-2
%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
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:
%if the read was successful, convert the string to integer:
{cvi} if
which will read the conversion operator 'cvi' (convert to integer) and the boolean and execute the former if the latter is true.
[edit] PowerShell
$string = Read-Host "Input a string"
[int]$number = Read-Host "Input a number"
[edit] 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
[edit] Python
[edit] Input a string
string = raw_input("Input a string: ")
In Python 3.0, raw_input will be renamed to input(). The Python 3.0 equivalent would be
string = input("Input a string: ")
[edit] 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.
number = input("Input a number: ") # Deprecated, please don't use.
Python 3.0 equivalent:
number = eval(input("Input a number: ")) # Evil, please don't use.
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.
number = float(raw_input("Input a number: "))
Python 3.0 equivalent:
number = float(input("Input a number: "))
float may be replaced by any numeric type, such as int, complex, or decimal.Decimal. Each one varies in expected input.
[edit] R
Works with: R version 2.81
stringval <- readline("String: ")
intval <- as.integer(readline("Integer: "))
[edit] Raven
'Input a string: ' print expect as str
'Input an integer: ' print expect 0 prefer as num
[edit] 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 "'."]
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...'.
[edit] REXX
do until i = 75000
say "Input 75000"
pull i
end
[edit] Ruby
Works with: Ruby version 1.8.4
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}"
[edit] Scheme
The read procedure is R5RS standard, inputs a scheme representation so, in order to read a string, one must enter "hello world"
(define str (read))
(define num (read))
(display "String = ") (display str)
(display "Integer = ") (display num)
[edit] 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.
[edit] Smalltalk
'Enter a number: ' display.
a := stdin nextLine asInteger.
'Enter a string: ' display.
b := stdin nextLine.
[edit] SNOBOL4
output = "Enter a string:"
str = trim(input)
output = "Enter an integer:"
int = trim(input)
output = "String: " str " Integer: " int
end
[edit] Standard ML
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
[edit] 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 str [gets stdin]
set num [gets stdin]
possibly followed by something like
if {![string is integer -strict $num]} then { ...do something here...}
If the requirement is to prompt until the user enters the integer 75000, then:
set input 0
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:
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"
[edit] TI-83 BASIC
This program leaves the string in String1, and the integer in variable "i".
:Input "Enter a string:",Str1
:Prompt i
:If(i ≠ 75000): Then
:Disp "That isn't 75000"
:Else
:Stop
[edit] TI-89 BASIC
This program leaves the requested values in the global variables s and integer.
Prgm
InputStr "Enter a string", s
Loop
Prompt integer
If integer ≠ 75000 Then
Disp "That wasn't 75000."
Else
Exit
EndIf
EndLoop
EndPrgm
[edit] 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
[edit] UNIX Shell
Works with: Debian Almquish SHell
#!/bin/sh
read STRING
read INTEGER
Works with: Bourne Again SHell
#!/bin/bash
read STRING
read INTEGER
[edit] Vedit macro language
Get_Input(1, "Enter a string: ")
#2 = Get_Num("Enter a number: ")
[edit] Visual Basic .NET
Platform: .NET
Works with: Visual Basic .NET version 9.0+
[edit] Input an Integer
Dim i As Integer
Console.WriteLine("Enter an Integer")
i = Console.ReadLine()
[edit] Input an Integer With Error Handling
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
[edit] Input a String
Dim i As String
Console.WriteLine("Enter a String")
i = Console.ReadLine()

