User input/Text: Difference between revisions

From Rosetta Code
Content added Content deleted
(Rename Perl 6 -> Raku, alphabetize, minor clean-up)
(→‎{{header|BabyCobol}}: conform to the task definition)
 
(48 intermediate revisions by 32 users not shown)
Line 1: Line 1:
{{task|Text processing}}
{{task|Text processing}}{{selection|Short Circuit|Console Program Basics}}[[Category:Basic language learning]][[Category:Keyboard Input]] [[Category:Simple]]
{{selection|Short Circuit|Console Program Basics}}
In this task, the goal is to input a string and the integer 75000, from the text console.
[[Category:Basic language learning]]
[[Category:Keyboard input]]
[[Category:Simple]]

;Task:
Input a string and the integer   '''75000'''   from the text console.


See also: [[User input/Graphical]]
See also: [[User input/Graphical]]
<br><br>


=={{header|AArch64 Assembly}}==
=={{header|11l}}==
<syntaxhighlight lang="11l">V string = input(‘Input a string: ’)
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
V number = Float(input(‘Input a number: ’))</syntaxhighlight>
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program inputText64.s */


=={{header|AArch64 Assembly}}==
/*******************************************/
{{works with|as|Raspberry Pi 3B/4 version Buster 64 bits}}
/* Constantes file */
<syntaxhighlight lang="aarch64 assembly">
/*******************************************/
//Consts
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ BUFFERSIZE, 100
.equ BUFFERSIZE, 100
.equ STDIN, 0 // linux input console
/*******************************************/
/* Initialized data */
.equ STDOUT, 1 // linux output console
.equ READ, 63
/*******************************************/
.equ WRITE, 64
.equ EXIT, 93

.data
.data
szMessDeb: .asciz "Enter text : \n"
enterText: .asciz "Enter text: "
szMessNum: .asciz "Enter number : \n"
carriageReturn: .asciz "\n"

szCarriageReturn: .asciz "\n"
//Read Buffer
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
.bss
sBuffer: .skip BUFFERSIZE
buffer: .skip BUFFERSIZE

/*******************************************/
/* code section */
/*******************************************/
.text
.text
.global main
.global _start
main: // entry of program
ldr x0,qAdrszMessDeb
bl affichageMess
mov x0,STDIN // Linux input console
ldr x1,qAdrsBuffer // buffer address
mov x2,BUFFERSIZE // buffer size
mov x8,READ // request to read datas
svc 0 // call system
ldr x1,qAdrsBuffer // buffer address
mov x2,#0 // end of string
strb w2,[x1,x0] // store byte at the end of input string (x0 contains number of characters)
ldr x0,qAdrsBuffer // buffer address
bl affichageMess
ldr x0,qAdrszCarriageReturn
bl affichageMess
ldr x0,qAdrszMessNum
bl affichageMess
mov x0,STDIN // Linux input console
ldr x1,qAdrsBuffer // buffer address
mov x2,BUFFERSIZE // buffer size
mov x8,READ // request to read datas
svc 0 // call system
ldr x1,qAdrsBuffer // buffer address
mov x2,#0 // end of string
strb w2,[x1,x0] // store byte at the end of input string (x0
//
ldr x0,qAdrsBuffer // buffer address
bl conversionAtoD // conversion string in number in x0
100: /* standard end of the program */
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc 0 // perform the system call
qAdrszMessDeb: .quad szMessDeb
qAdrszMessNum: .quad szMessNum
qAdrsBuffer: .quad sBuffer
qAdrszCarriageReturn: .quad szCarriageReturn
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


quadEnterText: .quad enterText
</lang>
quadBuffer: .quad buffer
quadCarriageReturn: .quad carriageReturn

writeMessage:
mov x2,0 // reset size counter to 0

checkSize: // get size of input
ldrb w1,[x0,x2] // load char with offset of x2
add x2,x2,#1 // add 1 char read legnth
cbz w1,output // if char found
b checkSize // loop

output:
mov x1,x0 // move string address into system call func parm
mov x0,STDOUT
mov x8,WRITE
svc 0 // trigger system write
ret


_start:
//Output enter text
ldr x0,quadEnterText // load enter message
bl writeMessage // output enter message

//Read User Input
mov x0,STDIN // linux input console
ldr x1,quadBuffer // load buffer address
mov x2,BUFFERSIZE // load buffer size
mov x8,READ // request to read data
svc 0 // trigger system read input

//Output User Message
mov x2, #0 // prep end of string
ldr x1,quadBuffer // load buffer address
strb w2,[x1, x0] // store x2 0 byte at the end of input string, offset x0
ldr x0,quadBuffer // load buffer address
bl writeMessage
//Output newline
ldr x0,quadCarriageReturn
bl writeMessage

//End Program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc 0 // trigger end of program

</syntaxhighlight>

=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
{{libheader|Action! Real Math}}
<syntaxhighlight lang="action!">INCLUDE "H6:REALMATH.ACT"

PROC Main()
CHAR ARRAY sUser(255)
REAL r75000,rUser

Put(125) PutE() ;clear the screen
ValR("75000",r75000)

Print("Please enter a text: ")
InputS(sUser)

DO
Print("Please enter number ")
PrintR(r75000) Print(": ")
InputR(rUser)
UNTIL RealEqual(rUser,r75000)
OD

PutE()
Print("Text: ") PrintE(sUser)
Print("Number: ") PrintRE(rUser)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/User_input_Text.png Screenshot from Atari 8-bit computer]
<pre>
Please enter a text: Atari 130XE
Please enter number 75000: 123
Please enter number 75000: 76000
Please enter number 75000: 75000

Text: Atari 130XE
Number: 75000
</pre>


=={{header|Ada}}==
=={{header|Ada}}==
{{works with|GCC|4.1.2}}
{{works with|GCC|4.1.2}}
<lang ada>function Get_String return String is
<syntaxhighlight lang="ada">function Get_String return String is
Line : String (1 .. 1_000);
Line : String (1 .. 1_000);
Last : Natural;
Last : Natural;
Line 97: Line 142:
-- may raise exception Constraint_Error if value entered is not a well-formed integer
-- may raise exception Constraint_Error if value entered is not a well-formed integer
end Get_Integer;
end Get_Integer;
</syntaxhighlight>
</lang>


The functions above may be called as shown below
The functions above may be called as shown below
<lang ada>My_String : String := Get_String;
<syntaxhighlight lang="ada">My_String : String := Get_String;
My_Integer : Integer := Get_Integer;</lang>
My_Integer : Integer := Get_Integer;</syntaxhighlight>


Another:
Another:
<lang ada>with Ada.Text_IO, Ada.Integer_Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO, Ada.Integer_Text_IO;


procedure User_Input is
procedure User_Input is
Line 119: Line 164:
Ada.Text_IO.Put_Line (Integer'Image(I));
Ada.Text_IO.Put_Line (Integer'Image(I));
end User_Input;
end User_Input;
</syntaxhighlight>
</lang>


Unbounded IO:
Unbounded IO:
<lang ada>with
<syntaxhighlight lang="ada">with
Ada.Text_IO,
Ada.Text_IO,
Ada.Integer_Text_IO,
Ada.Integer_Text_IO,
Line 140: Line 185:
Ada.Text_IO.Put_Line(Integer'Image(I));
Ada.Text_IO.Put_Line(Integer'Image(I));
end User_Input2;
end User_Input2;
</syntaxhighlight>
</lang>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
<lang algol68>print("Enter a string: ");
<syntaxhighlight 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>
~</syntaxhighlight>


=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
<lang algolw>begin
<syntaxhighlight lang="algolw">begin
string(80) s;
string(80) s;
integer n;
integer n;
Line 157: Line 202:
write( "Enter an integer> " );
write( "Enter an integer> " );
read( n )
read( n )
end.</lang>
end.</syntaxhighlight>

=={{header|Amazing Hopper}}==
Version: hopper-FLOW!
<syntaxhighlight lang="amazing hopper">
#include <flow.h>

#import lib/input.bas.lib
#include include/flow-input.h

DEF-MAIN(argv,argc)
CLR-SCR
MSET( número, cadena )
LOCATE(2,2), PRNL( "Input an string : "), LOC-COL(20), LET( cadena := READ-STRING( cadena ) )
LOCATE(3,2), PRNL( "Input an integer: "), LOC-COL(20), LET( número := INT( VAL(READ-NUMBER( número )) ) )
LOCATE(5,2), PRNL( cadena, "\n ",número )
END
</syntaxhighlight>
{{out}}
<pre>
Input an string : Juanita Pérez
Input an integer: 75000.789

Juanita Pérez
75000
</pre>


=={{header|APL}}==
=={{header|APL}}==
<lang APL>str←⍞
<syntaxhighlight lang="apl">str←⍞
int←⎕</lang>
int←⎕</syntaxhighlight>


=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>


/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
Line 317: Line 387:
szMessErrDep: .asciz "Too large: overflow 32 bits.\n"
szMessErrDep: .asciz "Too large: overflow 32 bits.\n"


</syntaxhighlight>
</lang>


=={{header|Arturo}}==
=={{header|Arturo}}==


<lang arturo>print "Enter a string: "
<syntaxhighlight lang="rebol">str: input "Enter a string: "
num: to :integer input "Enter an integer: "
str: strip|input ~


print ["Got:" str "," num]</syntaxhighlight>
print "Enter an integer: "
num: toNumber|strip|input ~

print "Got: " + str + ", " + num</lang>


{{out}}
{{out}}


<pre>Enter a string:
<pre>Enter a string: hello world
Enter an integer: 1986
hello
Got: hello world , 1986</pre>
Enter an integer:
75000
Got: hello, 75000</pre>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
===Windows console===
===Windows console===
<lang AutoHotkey>DllCall("AllocConsole")
<syntaxhighlight lang="autohotkey">DllCall("AllocConsole")
FileAppend, please type something`n, CONOUT$
FileAppend, please type something`n, CONOUT$
FileReadLine, line, CONIN$, 1
FileReadLine, line, CONIN$, 1
Line 345: Line 410:
FileAppend, please type '75000'`n, CONOUT$
FileAppend, please type '75000'`n, CONOUT$
FileReadLine, line, CONIN$, 1
FileReadLine, line, CONIN$, 1
msgbox % line</lang>
msgbox % line</syntaxhighlight>


===Input Command===
===Input Command===
this one takes input regardless of which application has focus.
this one takes input regardless of which application has focus.
<lang AutoHotkey>TrayTip, Input:, Type a string:
<syntaxhighlight lang="autohotkey">TrayTip, Input:, Type a string:
Input(String)
Input(String)
TrayTip, Input:, Type an int:
TrayTip, Input:, Type an int:
Line 371: Line 436:
TrayTip, Input:, %Output%
TrayTip, Input:, %Output%
}
}
}</lang>
}</syntaxhighlight>


=={{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}'
<syntaxhighlight 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</lang>
ok,75000/75000</syntaxhighlight>


=={{header|Axe}}==
=={{header|Axe}}==
Line 388: 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.
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.


<lang axe>Disp "String:"
<syntaxhighlight lang="axe">Disp "String:"
input→A
input→A
length(A)→L
length(A)→L
Line 422: Line 487:
If C≠7500
If C≠7500
Disp "That isn't 7500"
Disp "That isn't 7500"
End</lang>
End</syntaxhighlight>

=={{header|BabyCobol}}==
<syntaxhighlight lang="cobol">
* NB: whitespace insignificance and case insensitivity
* are used in the field name.
IDENTIFICATION DIVISION.
PROGRAM-ID. USER INPUT.
DATA DIVISION.
01 HUNDRED CHAR STRING PICTURE IS X(100).
01 FIVE DIGIT NUMBER PICTURE IS 9(5).
PROCEDURE DIVISION.
DISPLAY "Enter a string of appropriate length: " WITH NO ADVANCING
ACCEPT HundredChar String.
DISPLAY "Enter a number (preferably 75000): " WITH NO ADVANCING
ACCEPT FiveDigit Number.
</syntaxhighlight>


=={{header|BASIC}}==
=={{header|BASIC}}==
Line 431: Line 512:
This isn't a hard-and-fast rule -- for example, [[Chipmunk Basic]] ''never'' appends a question mark.
This isn't a hard-and-fast rule -- for example, [[Chipmunk Basic]] ''never'' appends a question mark.


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


Output ([[QBasic]]):
Output ([[QBasic]]):
Line 438: Line 519:
Enter a number: 1
Enter a number: 1
==={{header|Applesoft BASIC}}===
==={{header|Applesoft BASIC}}===
<lang basic>10 INPUT "ENTER A STRING: "; S$
<syntaxhighlight lang="basic">10 INPUT "ENTER A STRING: "; S$
20 INPUT "ENTER A NUMBER: "; I : I = INT(I)</lang>
20 INPUT "ENTER A NUMBER: "; I : I = INT(I)</syntaxhighlight>

==={{header|Commodore BASIC}}===
When using the prompt feature of the <code>INPUT</code> command, the string literal must be followed by a semicolon and then the string variable, or else a <code>?SYNTAX ERROR</code> will occur. The question mark prompt is always presented with the <code>INPUT</code> command. Any other behavior would have to come from a user-built routine using the <code>GET</code> command.

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.

<syntaxhighlight lang="gwbasic">
10 input "what is a word i should remember";a$
20 print "thank you."
30 input "will you please type the number 75000";nn
40 if nn<>75000 then print "i'm sorry, that's not right.":goto 30
50 print "thank you.":print "you provided the following values:"
60 print a$
70 print nn
80 end
</syntaxhighlight>

'''Output'''
<pre>
READY.
RUN
WHAT IS A WORD I SHOULD REMEMBER? PANCAKE
THANK YOU.
WILL YOU PLEASE TYPE THE NUMBER 75000? NO.
?REDO FROM START
WILL YOU PLEASE TYPE THE NUMBER 75000? 848
I'M SORRY, THAT'S NOT RIGHT.
WILL YOU PLEASE TYPE THE NUMBER 75000? 75000
THANK YOU.
YOU PROVIDED THE FOLLOWING VALUES:
PANCAKE
75000

READY.
&#9608;
</pre>


==={{header|IS-BASIC}}===
==={{header|IS-BASIC}}===
<lang IS-BASIC>100 INPUT PROMPT "Enter a number: ":NUM
<syntaxhighlight lang="is-basic">100 INPUT PROMPT "Enter a number: ":NUM
110 INPUT PROMPT "Enter a string: ":ST$</lang>
110 INPUT PROMPT "Enter a string: ":ST$</syntaxhighlight>

==={{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.
<syntaxhighlight lang="qb64">Input "Enter text and a number", s$, l&
Print s$
Print l&
</syntaxhighlight>

==={{header|BASIC256}}===
<syntaxhighlight lang="freebasic">input string "Please enter a string: ", s
do
input "Please enter 75000 : ", i
until i = 75000
print
print s, i</syntaxhighlight>

==={{header|Run BASIC}}===
<syntaxhighlight lang="runbasic">input "Please enter a string: "; s$
while i <> 75000
input "Please enter 75000 : "; i
wend
print
print s$; chr$(9); i</syntaxhighlight>

==={{header|True BASIC}}===
{{works with|QBasic}}
<syntaxhighlight lang="qbasic">PRINT "Please enter a string";
INPUT s$
DO
PRINT "Please enter 75000 ";
INPUT i
LOOP Until i = 75000
PRINT
PRINT s$, i
END</syntaxhighlight>

==={{header|Yabasic}}===
<syntaxhighlight lang="freebasic">input "Please enter a string: " s$
repeat
input "Please enter 75000 : " i
until i = 75000
print
print s$, chr$(9), i</syntaxhighlight>


==={{header|Sinclair ZX81 BASIC}}===
==={{header|Sinclair ZX81 BASIC}}===
<lang basic>10 PRINT "ENTER A STRING"
<syntaxhighlight lang="basic">10 PRINT "ENTER A STRING"
20 INPUT S$
20 INPUT S$
30 PRINT "YOU ENTERED: ";S$
30 PRINT "YOU ENTERED: ";S$
Line 453: Line 613:
60 IF N=75000 THEN STOP
60 IF N=75000 THEN STOP
70 PRINT "NO, ";
70 PRINT "NO, ";
80 GOTO 40</lang>
80 GOTO 40</syntaxhighlight>


=={{header|Batch File}}==
=={{header|Batch File}}==


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


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
<lang bbcbasic> INPUT LINE "Enter a string: " string$
<syntaxhighlight lang="bbcbasic"> INPUT LINE "Enter a string: " string$
INPUT "Enter a number: " number
INPUT "Enter a number: " number
PRINT "String = """ string$ """"
PRINT "String = """ string$ """"
PRINT "Number = " ; number</lang>
PRINT "Number = " ; number</syntaxhighlight>


=={{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).
<lang befunge><>:v:"Enter a string: "
<syntaxhighlight lang="befunge"><>:v:"Enter a string: "
^,_ >~:1+v
^,_ >~:1+v
^ _@</lang>
^ _@</syntaxhighlight>


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


=={{header|Bracmat}}==
=={{header|Bracmat}}==
<lang bracmat>( doit
<syntaxhighlight lang="bracmat">( doit
= out'"Enter a string"
= out'"Enter a string"
& get':?mystring
& get':?mystring
Line 489: Line 649:
)
)
& out$(mystring is !mystring \nmynumber is !mynumber \n)
& out$(mystring is !mystring \nmynumber is !mynumber \n)
);</lang>
);</syntaxhighlight>
<pre>{?} !doit
<pre>{?} !doit
Enter a string
Enter a string
Line 502: Line 662:


=={{header|C}}==
=={{header|C}}==
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>


Line 523: Line 683:


return EXIT_SUCCESS;
return EXIT_SUCCESS;
}</lang>
}</syntaxhighlight>

==={{libheader|Gadget}}===
<syntaxhighlight lang="c">
#include <gadget/gadget.h>

LIB_GADGET_START

Main
Cls;
String text;
int number=0;
At 5,5; Print "Enter text : ";
Atrow 7; Print "Enter ‘75000’: ";
Atcol 20;
Atrow 5; Fn_let(text, Input ( text, 30 ) );
Free secure text;
Atrow 7; Stack{
while (number!=75000 )
/*into stack, Input() not need var*/
number = Str2int( Input ( NULL, 6 ) );
}Stack_off;

Prnl;
End
</syntaxhighlight>
{{out}}
<pre>
$ ./tests/input_cons




Enter text : Juanita la mañosa

Enter ‘75000’: 75000
$
</pre>


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


namespace C_Sharp_Console {
namespace C_Sharp_Console {
Line 542: Line 743:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
{{works with|g++}}
{{works with|g++}}
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <string>
#include <string>
using namespace std;
using namespace std;
Line 561: Line 762:
cin >> string_input;
cin >> string_input;
return 0;
return 0;
}</lang>
}</syntaxhighlight>


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
<lang cpp> cin >> string_input;</lang>
<syntaxhighlight lang="cpp"> cin >> string_input;</syntaxhighlight>
with
with
<lang cpp> getline(cin, string_input);</lang>
<syntaxhighlight lang="cpp"> getline(cin, string_input);</syntaxhighlight>


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.
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 573: Line 774:


=={{header|Ceylon}}==
=={{header|Ceylon}}==
<lang ceylon>shared void run() {
<syntaxhighlight lang="ceylon">shared void run() {
print("enter any text here");
print("enter any text here");
value text = process.readLine();
value text = process.readLine();
print(text);
print(text);
print("enter the number 7500 here");
print("enter the number 75000 here");
value number = parseInteger(process.readLine() else "") else -1;
if (is Integer number = Integer.parse(process.readLine() else "")) {
print("``number == 7500 then number else "close enough"``");
print("``number == 75k then number else "close enough"``");
}
}</lang>
else {
print("That was not a number per se.");
}
}</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang lisp>(import '(java.util Scanner))
<syntaxhighlight 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))</lang>
(def n (.nextInt scan))</syntaxhighlight>


=={{header|COBOL}}==
=={{header|COBOL}}==
{{works with|OpenCOBOL}}
{{works with|OpenCOBOL}}
<lang cobol> IDENTIFICATION DIVISION.
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. Get-Input.
PROGRAM-ID. Get-Input.


Line 606: Line 811:


GOBACK
GOBACK
.</lang>
.</syntaxhighlight>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(format t "Enter some text: ")
<syntaxhighlight lang="lisp">(format t "Enter some text: ")
(let ((s (read-line)))
(let ((s (read-line)))
(format t "You entered ~s~%" s))
(format t "You entered ~s~%" s))
Line 617: Line 822:
(if (numberp n)
(if (numberp n)
(format t "You entered ~d.~%" n)
(format t "You entered ~d.~%" n)
(format t "That was not a number.")))</lang>
(format t "That was not a number.")))</syntaxhighlight>


=={{header|Crystal}}==
=={{header|Crystal}}==


<lang ruby>puts "You entered: #{gets}"
<syntaxhighlight lang="ruby">puts "You entered: #{gets}"


begin
begin
Line 627: Line 832:
rescue ex
rescue ex
puts ex
puts ex
end</lang>
end</syntaxhighlight>


Example with valid input:
Example with valid input:
Line 646: Line 851:


=={{header|D}}==
=={{header|D}}==
<lang D>import std.stdio;
<syntaxhighlight lang="d">import std.stdio;
void main() {
void main() {
Line 658: Line 863:
writeln("Read in '", number, "' and '", str, "'");
writeln("Read in '", number, "' and '", str, "'");
}</lang>
}</syntaxhighlight>


=={{header|Dart}}==
=={{header|Dart}}==
<lang javascript>import 'dart:io' show stdout, stdin;
<syntaxhighlight lang="javascript">import 'dart:io' show stdout, stdin;


main() {
main() {
Line 688: Line 893:
}
}


</syntaxhighlight>
</lang>


=={{header|Delphi}}==
=={{header|Delphi}}==
<lang Delphi>program UserInputText;
<syntaxhighlight lang="delphi">program UserInputText;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 712: Line 917:
Writeln('Invalid entry: ' + s);
Writeln('Invalid entry: ' + s);
until lIntegerValue = 75000;
until lIntegerValue = 75000;
end.</lang>
end.</syntaxhighlight>


=={{header|Déjà Vu}}==
=={{header|Déjà Vu}}==
<lang dejavu>input s:
<syntaxhighlight lang="dejavu">input s:
!print\ s
!print\ s
!decode!utf-8 !read-line!stdin
!decode!utf-8 !read-line!stdin
Line 725: Line 930:
/= 75000
/= 75000
catch value-error:
catch value-error:
true</lang>
true</syntaxhighlight>


=={{header|EasyLang}}==
=={{header|EasyLang}}==


<lang>write "Enter a string: "
<syntaxhighlight lang="text">write "Enter a string: "
a$ = input
a$ = input
print ""
print ""
Line 738: Line 943:
until h = 75000
until h = 75000
.
.
print a$ & " " & h</lang>
print a$ & " " & h</syntaxhighlight>


=={{header|Elena}}==
=={{header|Elena}}==
ELENA 4.x :
ELENA 6.x :
<lang elena>import extensions;
<syntaxhighlight lang="elena">import extensions;
public program()
public program()
{
{
var num := new Integer();
var num := new Integer();
console.write:"Enter an integer: ".loadLineTo:num;
console.write("Enter an integer: ").loadLineTo(num);
var word := console.write:"Enter a String: ".readLine()
var word := console.write("Enter a String: ").readLine()
}</lang>
}</syntaxhighlight>


=={{header|Elixir}}==
=={{header|Elixir}}==
<syntaxhighlight lang="elixir">
<lang Elixir>
a = IO.gets("Enter a string: ") |> String.strip
a = IO.gets("Enter a string: ") |> String.strip
b = IO.gets("Enter an integer: ") |> String.strip |> String.to_integer
b = IO.gets("Enter an integer: ") |> String.strip |> String.to_integer
Line 760: Line 965:
IO.puts "Integer = #{b}"
IO.puts "Integer = #{b}"
IO.puts "Float = #{f}"
IO.puts "Float = #{f}"
</syntaxhighlight>
</lang>


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>{ok, [String]} = io:fread("Enter a string: ","~s").
<syntaxhighlight 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").</syntaxhighlight>


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


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang Euphoria>include get.e
<syntaxhighlight lang="euphoria">include get.e


sequence s
sequence s
Line 778: Line 983:
puts(1, s & '\n')
puts(1, s & '\n')
n = prompt_number("Enter a number:",{})
n = prompt_number("Enter a number:",{})
printf(1, "%d", n)</lang>
printf(1, "%d", n)</syntaxhighlight>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>open System
<syntaxhighlight lang="fsharp">open System


let ask_for_input s =
let ask_for_input s =
Line 791: Line 996:
ask_for_input "Input a string" |> ignore
ask_for_input "Input a string" |> ignore
ask_for_input "Enter the number 75000" |> ignore
ask_for_input "Enter the number 75000" |> ignore
0</lang>
0</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>"Enter a string: " write
<syntaxhighlight lang="factor">"Enter a string: " write
readln
readln
"Enter a number: " write
"Enter a number: " write
readln string>number</lang>
readln string>number</syntaxhighlight>


=={{header|Falcon}}==
=={{header|Falcon}}==
<lang falcon>printl("Enter a string:")
<syntaxhighlight lang="falcon">printl("Enter a string:")
str = input()
str = input()
printl("Enter a number:")
printl("Enter a number:")
n = int(input())</lang>
n = int(input())</syntaxhighlight>


=={{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 (^).
<lang false>[[^$' =~][,]#,]w:
<syntaxhighlight lang="false">[[^$' =~][,]#,]w:
[0[^'0-$$9>0@>|~][\10*+]#%]d:
[0[^'0-$$9>0@>|~][\10*+]#%]d:
w;! d;!.</lang>
w;! d;!.</syntaxhighlight>


=={{header|Fantom}}==
=={{header|Fantom}}==
Line 815: Line 1,020:
The 'toInt' method on an input string will throw an exception if the input is not a number.
The 'toInt' method on an input string will throw an exception if the input is not a number.


<lang fantom>
<syntaxhighlight lang="fantom">
class Main
class Main
{
{
Line 834: Line 1,039:
}
}
}
}
</syntaxhighlight>
</lang>


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


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


===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 )
<syntaxhighlight 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 ;</syntaxhighlight>


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


{{works with|Win32Forth}}
{{works with|Win32Forth}}
<lang forth>: INPUT# ( -- n true | false )
<syntaxhighlight 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 ;</syntaxhighlight>


Note that NUMBER? always leaves a double result on the stack.
Note that NUMBER? always leaves a double result on the stack.
Line 863: Line 1,068:


{{works with|4tH}}
{{works with|4tH}}
<lang forth>: input#
<syntaxhighlight lang="forth">: input#
begin
begin
refill drop bl parse-word ( a n)
refill drop bl parse-word ( a n)
Line 870: Line 1,075:
drop ( --)
drop ( --)
repeat ( n)
repeat ( n)
;</lang>
;</syntaxhighlight>


Here is an example that puts it all together:
Here is an example that puts it all together:


<lang forth>: TEST
<syntaxhighlight 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 ;</syntaxhighlight>


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


Line 889: Line 1,094:
read*, s
read*, s
print*, "Enter the integer 75000"
print*, "Enter the integer 75000"
read*, i</lang>
read*, i</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Dim s As String
Dim s As String
Line 902: Line 1,107:
Print
Print
Print s, i
Print s, i
Sleep</lang>
Sleep</syntaxhighlight>
Sample input/output
Sample input/output
{{out}}
{{out}}
Line 914: Line 1,119:


=={{header|Frink}}==
=={{header|Frink}}==
<lang frink>
<syntaxhighlight lang="frink">
s = input["Enter a string: "]
s = input["Enter a string: "]
i = parseInt[input["Enter an integer: "]]
i = parseInt[input["Enter an integer: "]]
</syntaxhighlight>
</lang>

=={{header|GDScript}}==
{{works with|Godot|4.0}}

Run with <code>godot --headless --script <file></code>

<syntaxhighlight lang="gdscript">
extends MainLoop

func _process(_delta: float) -> bool:
printraw("Input a string: ")
var read_line := OS.read_string_from_stdin() # Mote that this retains the newline.

printraw("Input an integer: ")
var read_integer := int(OS.read_string_from_stdin())

print("read_line = %s" % read_line.trim_suffix("\n"))
print("read_integer = %d" % read_integer)

return true # Exit instead of looping
</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
Go has C-like Scan and Scanf functions for quick and dirty input:
Go has C-like Scan and Scanf functions for quick and dirty input:
<lang go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 933: Line 1,159:
fmt.Println("wrong")
fmt.Println("wrong")
}
}
}</lang>
}</syntaxhighlight>
Code below allows much more control over interaction and error checking.
Code below allows much more control over interaction and error checking.
<syntaxhighlight lang="go">
<lang go>
package main
package main


Line 974: Line 1,200:
fmt.Println("Good")
fmt.Println("Good")
}
}
</syntaxhighlight>
</lang>


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


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>import System.IO (hFlush, stdout)
<syntaxhighlight lang="haskell">import System.IO (hFlush, stdout)
main = do
main = do
putStr "Enter a string: "
putStr "Enter a string: "
Line 989: Line 1,215:
hFlush stdout
hFlush stdout
num <- readLn :: IO Int
num <- readLn :: IO Int
putStrLn $ str ++ (show num)</lang>
putStrLn $ str ++ (show num)</syntaxhighlight>
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|hexiscript}}==
=={{header|hexiscript}}==
<lang hexiscript>print "Enter a string: "
<syntaxhighlight lang="hexiscript">print "Enter a string: "
let s scan str
let s scan str
print "Enter a number: "
print "Enter a number: "
let n scan int</lang>
let n scan int</syntaxhighlight>


=={{header|HolyC}}==
=={{header|HolyC}}==
<lang holyc>U8 *s;
<syntaxhighlight lang="holyc">U8 *s;
s = GetStr("Enter a string: ");
s = GetStr("Enter a string: ");


Line 1,009: Line 1,235:


Print("Your string: %s\n", s);
Print("Your string: %s\n", s);
Print("75000: %d\n", Str2I64(n));</lang>
Print("75000: %d\n", Str2I64(n));</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
Line 1,015: Line 1,241:
The following works in both Icon and Unicon:
The following works in both Icon and Unicon:


<lang icon>
<syntaxhighlight lang="icon">
procedure main ()
procedure main ()
writes ("Enter something: ")
writes ("Enter something: ")
Line 1,026: Line 1,252:
else write ("you must enter a number")
else write ("you must enter a number")
end
end
</syntaxhighlight>
</lang>


=={{header|Io}}==
=={{header|Io}}==
<lang io>string := File clone standardInput readLine("Enter a string: ")
<syntaxhighlight lang="io">string := File clone standardInput readLine("Enter a string: ")
integer := File clone standardInput readLine("Enter 75000: ") asNumber</lang>
integer := File clone standardInput readLine("Enter 75000: ") asNumber</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
'''Solution'''
'''Solution'''
<lang j> require 'misc' NB. load system script
<syntaxhighlight lang="j"> require 'misc' NB. load system script
prompt 'Enter string: '
prompt 'Enter string: '
0".prompt 'Enter an integer: '</lang>
0".prompt 'Enter an integer: '</syntaxhighlight>


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.
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'''
'''Example Usage'''
<lang j> prompt 'Enter string: ' NB. output string to session
<syntaxhighlight lang="j"> prompt 'Enter string: ' NB. output string to session
Enter string: Hello World
Enter string: Hello World
Hello World
Hello World
Line 1,055: Line 1,281:
│Hello Rosetta Code│75000│
│Hello Rosetta Code│75000│
└──────────────────┴─────┘
└──────────────────┴─────┘
</syntaxhighlight>
</lang>


=={{header|Java}}==
=={{header|Java}}==


<lang java>
<syntaxhighlight lang="java">
import java.util.Scanner;
import java.util.Scanner;


Line 1,070: Line 1,296:
int i = Integer.parseInt(s.next());
int i = Integer.parseInt(s.next());
}
}
}</lang>
}</syntaxhighlight>


or
or


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


public class GetInput {
public class GetInput {
Line 1,083: Line 1,309:
int number = stdin.nextInt();
int number = stdin.nextInt();
}
}
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
{{works with|JScript}} and only with <code>cscript.exe</code>
{{works with|JScript}} and only with <code>cscript.exe</code>
<lang javascript>WScript.Echo("Enter a string");
<syntaxhighlight lang="javascript">WScript.Echo("Enter a string");
var str = WScript.StdIn.ReadLine();
var str = WScript.StdIn.ReadLine();


Line 1,094: Line 1,320:
WScript.Echo("Enter the integer 75000");
WScript.Echo("Enter the integer 75000");
val = parseInt( WScript.StdIn.ReadLine() );
val = parseInt( WScript.StdIn.ReadLine() );
}</lang>
}</syntaxhighlight>


{{works with|SpiderMonkey}}
{{works with|SpiderMonkey}}
<lang javascript>print("Enter a string");
<syntaxhighlight lang="javascript">print("Enter a string");
var str = readline();
var str = readline();


Line 1,104: Line 1,330:
print("Enter the integer 75000");
print("Enter the integer 75000");
val = parseInt( readline() );
val = parseInt( readline() );
}</lang>
}</syntaxhighlight>


=={{header|Joy}}==
=={{header|Joy}}==
<syntaxhighlight lang="joy">
<lang Joy>
"Enter a string: " putchars
"Enter a string: " putchars
stdin fgets
stdin fgets
"Enter a number: " putchars
"Enter a number: " putchars
stdin fgets 10 strtol.
stdin fgets 10 strtol.
</syntaxhighlight>
</lang>


=={{header|jq}}==
=={{header|jq}}==
Line 1,124: Line 1,350:
encountered, then the following program could be used on the assumption that
encountered, then the following program could be used on the assumption that
the inputs are all valid JSON.
the inputs are all valid JSON.
<lang jq>def read(int):
<syntaxhighlight lang="jq">def read(int):
null | until( . == int; "Expecting \(int)" | stderr | input);
null | until( . == int; "Expecting \(int)" | stderr | input);
Line 1,131: Line 1,357:


(read_string | "I see the string: \(.)"),
(read_string | "I see the string: \(.)"),
(read(75000) | "I see the expected integer: \(.)")</lang>
(read(75000) | "I see the expected integer: \(.)")</syntaxhighlight>
{{out}}
{{out}}
The following is a transcript showing the prompts (on stderr), responses (on stdin) and output (on stdout):
The following is a transcript showing the prompts (on stderr), responses (on stdin) and output (on stdout):
<lang sh>$ jq -n -r -f User_input.jq
<syntaxhighlight lang="sh">$ jq -n -r -f User_input.jq
"Please enter a string"
"Please enter a string"
1
1
Line 1,146: Line 1,372:
"Expecting 75000"
"Expecting 75000"
75000
75000
I see the expected integer: 75000</lang>
I see the expected integer: 75000</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
{{works with|Julia|0.6}}
{{works with|Julia|0.6}}
<syntaxhighlight lang="julia">
<lang Julia>
print("String? ")
print("String? ")
y = readline()
y = readline()
Line 1,162: Line 1,388:
println("Sorry, but \"", y, "\" does not compute as an integer.")
println("Sorry, but \"", y, "\" does not compute as an integer.")
end
end
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,181: Line 1,407:


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


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1
<syntaxhighlight lang="scala">// version 1.1


fun main(args: Array<String>) {
fun main(args: Array<String>) {
Line 1,197: Line 1,423:
val number = readLine()!!.toInt()
val number = readLine()!!.toInt()
} while (number != 75000)
} while (number != 75000)
}</lang>
}</syntaxhighlight>

=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{input
{@ type="text"
placeholder="Please enter a string and dblclick"
ondblclick="alert( 'You wrote « ' +
this.value +
' » and it is ' +
((isNaN(this.value)) ? 'not' : '') +
' a number.' )"
}}

Please enter a string and dblclick

Input: Hello World
Output: You wrote « Hello World » and it is not a number.

Input: 123
Output: You wrote « 123 » and it is a number.

</syntaxhighlight>


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>#!/usr/bin/lasso9
<syntaxhighlight lang="lasso">#!/usr/bin/lasso9


define read_input(prompt::string) => {
define read_input(prompt::string) => {
Line 1,230: Line 1,478:


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


Output:
Output:
Line 1,237: Line 1,485:
Hello (string) | 1234 (integer)
Hello (string) | 1234 (integer)
</pre>
</pre>

=={{header|LDPL}}==
<syntaxhighlight lang="ldpl">data:
myText is text
myNumber is number

procedure:
display "Enter some text: "
accept myText
display "Enter a number: "
accept myNumber
</syntaxhighlight>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<lang lb>Input "Enter a string. ";string$
<syntaxhighlight lang="lb">Input "Enter a string. ";string$
Input "Enter the value 75000.";num</lang>
Input "Enter the value 75000.";num</syntaxhighlight>


=={{header|LIL}}==
=={{header|LIL}}==
<lang tcl># User input/text, in LIL
<syntaxhighlight lang="tcl"># User input/text, in LIL
write "Enter a string: "
write "Enter a string: "
set text [readline]
set text [readline]
Line 1,254: Line 1,514:


print $text
print $text
print $num</lang>
print $num</syntaxhighlight>


=={{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
<syntaxhighlight lang="logo">make "input readlist ; in: string 75000
show map "number? :input ; [false true]
show map "number? :input ; [false true]


Line 1,264: Line 1,524:
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</syntaxhighlight>


=={{header|Logtalk}}==
=={{header|Logtalk}}==
Using an atom representation for strings and type-check failure-driven loops:
Using an atom representation for strings and type-check failure-driven loops:
<lang logtalk>
<syntaxhighlight lang="logtalk">
:- object(user_input).
:- object(user_input).


Line 1,285: Line 1,545:


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


=={{header|LOLCODE}}==
=={{header|LOLCODE}}==
<lang LOLCODE>HAI 1.4
<syntaxhighlight lang="lolcode">HAI 1.4
I HAS A string
I HAS A string
GIMMEH string
GIMMEH string
Line 1,303: Line 1,563:
MAEK number A NUMBR
MAEK number A NUMBR
KTHXBYE
KTHXBYE
</syntaxhighlight>
</lang>


=={{header|Lua}}==
=={{header|Lua}}==
<lang Lua>print('Enter a string: ')
<syntaxhighlight lang="lua">print('Enter a string: ')
s = io.stdin:read()
s = io.stdin:read()
print('Enter a number: ')
print('Enter a number: ')
i = tonumber(io.stdin:read())
i = tonumber(io.stdin:read())
</syntaxhighlight>
</lang>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckIt {
Module CheckIt {
Keyboard "75000"+chr$(13)
Keyboard "75000"+chr$(13)
Line 1,323: Line 1,583:
}
}
CheckIt
CheckIt
</syntaxhighlight>
</lang>

=={{header|MACRO-10}}==
<syntaxhighlight lang="macro-10">
TITLE User Input

COMMENT !
User Input ** PDP-10 assembly language (kjx, 2022)
Assembler: MACRO-10 Operating system: TOPS-20

This program reads a string (maximum of 80 characters) and
a decimal number. The number is checked to be 75000. Invalid
input (like entering characters instead of a decimal number)
is detected, and an error message is printed in that case.
!

SEARCH MONSYM,MACSYM
.REQUIRE SYS:MACREL

STDAC. ;Set standard register names.

STRING: BLOCK 20 ;20 octal words = 80 characters.
NUMBER: BLOCK 1 ;1 word for number.

;;
;; Execution starts here:
;;

GO:: RESET% ;Initialize process.

;; Print prompt:

HRROI T1,[ASCIZ /Please type a string, 80 chars max.: /]
PSOUT%
;; Read string from terminal:

HRROI T1,STRING ;Pointer to string-buffer.
MOVEI T2,^D80 ;80 characters max.
SETZ T3 ;No special ctrl-r prompt.
RDTTY% ;Read from terminal.
ERJMP ERROR ; On error, go to ERROR.

;; Print second prompt:

NUMI: HRROI T1,[ASCIZ /Please type the decimal number 75000: /]
PSOUT%
;; Input number from terminal:
MOVEI T1,.PRIIN ;Read from terminal.
MOVEI T3,^D10 ;Decimal input.
NIN% ;Input number.
ERJMP ERROR ; On error, go to ERROR.
;; Make sure number is actually 75000.
CAIE T2,^D75000 ;Compare number...
JRST [ HRROI T1,[ASCIZ /Number is not 75000! /]
PSOUT% ; ...complain and
JRST NUMI ] ; try again.
MOVEM T2,NUMBER ;Store number if correct.

;; Now print out string and number:

HRROI T1,STRING ;String ptr into T1.
PSOUT% ;Print string.

MOVEI T1,.PRIOU ;Print on standard output.
MOVE T2,NUMBER ;Load number into T2.
MOVEI T3,^D10 ;Decimal output.
NOUT% ;And print the number.
ERJMP ERROR ; On error, go to ERROR.

;; End program:

HALTF% ;Halt program.
JRST GO ;Allow for 'continue'-command.

;;
;; The following routine prints out an error message,
;; similar to perror() in C:
;;

ERROR: MOVEI T1,.PRIOU ;Standard output.
MOVE T2,[.FHSLF,,-1] ;Own program, last error.
SETZ T3, ;No size-limit on message.
ERSTR% ;Print error-message.
JFCL ; Ignore errors from ERSTR.
JFCL ; dito.
HALTF% ;Halt program.
JRST GO ;Allow for 'continue'-command.

END GO
</syntaxhighlight>
Example output:
<pre>
@ exec uinput
MACRO: User
LINK: Loading
[LNKXCT USER execution]
Please type a string, 80 chars max.: This is a test.
Please type the decimal number 75000: 74998
Number is not 75000! Please type the decimal number 75000: 74999
Number is not 75000! Please type the decimal number 75000: 75000
This is a test.
75000
@ _
</pre>


=={{header|Maple}}==
=={{header|Maple}}==
<lang maple>printf("String:"); string_value := readline();
<syntaxhighlight lang="maple">printf("String:"); string_value := readline();
printf("Integer: "); int_value := parse(readline());</lang>
printf("Integer: "); int_value := parse(readline());</syntaxhighlight>


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


=={{header|MATLAB}}==
=={{header|MATLAB}}==
Line 1,337: Line 1,705:


Sample usage:
Sample usage:
<lang MATLAB>>> input('Input string: ')
<syntaxhighlight lang="matlab">>> input('Input string: ')
Input string: 'Hello'
Input string: 'Hello'


Line 1,356: Line 1,724:
ans =
ans =


75000</lang>
75000</syntaxhighlight>

=={{header|Maxima}}==

<syntaxhighlight lang="maxima">
/* String routine */
block(
s:read("enter a string"),
if stringp(s) then print(s,"is an actual string") else "that is not a string")$

/* Number routine */
block(
n:read("enter a number"),
if numberp(n) then print(n,"is an actual number") else "that is not a number")$
</syntaxhighlight>


=={{header|Metafont}}==
=={{header|Metafont}}==


<lang metafont>string s;
<syntaxhighlight lang="metafont">string s;
message "write a string: ";
message "write a string: ";
s := readstring;
s := readstring;
Line 1,371: Line 1,753:
message "Sorry..."
message "Sorry..."
fi;
fi;
end</lang>
end</syntaxhighlight>


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).
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,377: Line 1,759:
=={{header|min}}==
=={{header|min}}==
{{works with|min|0.19.3}}
{{works with|min|0.19.3}}
<lang min>"Enter a string" ask
<syntaxhighlight lang="min">"Enter a string" ask
"Enter an integer" ask int</lang>
"Enter an integer" ask int</syntaxhighlight>


=={{header|Mirah}}==
=={{header|Mirah}}==
<lang mirah>s = System.console.readLine()
<syntaxhighlight lang="mirah">s = System.console.readLine()


puts s</lang>
puts s</syntaxhighlight>


=={{header|mIRC Scripting Language}}==
=={{header|mIRC Scripting Language}}==
<lang mirc>alias askmesomething {
<syntaxhighlight 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>
}</syntaxhighlight>


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


IMPORT IO, Fmt;
IMPORT IO, Fmt;
Line 1,404: Line 1,786:
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.</lang>
END Input.</syntaxhighlight>


=={{header|MUMPS}}==
=={{header|MUMPS}}==
<lang MUMPS>TXTINP
<syntaxhighlight lang="mumps">TXTINP
NEW S,N
NEW S,N
WRITE "Enter a string: "
WRITE "Enter a string: "
Line 1,414: Line 1,796:
READ N,!
READ N,!
KILL S,N
KILL S,N
QUIT</lang>
QUIT</syntaxhighlight>


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
<lang Nanoquery>string = str(input("Enter a string: "))
<syntaxhighlight lang="nanoquery">string = str(input("Enter a string: "))
integer = int(input("Enter an integer: "))</lang>
integer = int(input("Enter an integer: "))</syntaxhighlight>


=={{header|Neko}}==
=={{header|Neko}}==
<syntaxhighlight lang="actionscript">/**
<lang ActionScript>/**
User input/Text, in Neko
User input/Text, in Neko
Tectonics:
Tectonics:
Line 1,455: Line 1,837:
if num == 75000 $print("Rosetta Code 75000, for the win!\n")
if num == 75000 $print("Rosetta Code 75000, for the win!\n")
else $print("Sorry, need 75000\n")
else $print("Sorry, need 75000\n")
} catch problem $print("Exception: ", problem, "\n")</lang>
} catch problem $print("Exception: ", problem, "\n")</syntaxhighlight>


{{out}}
{{out}}
Line 1,467: Line 1,849:


=={{header|Nemerle}}==
=={{header|Nemerle}}==
<lang Nemerle>using System;
<syntaxhighlight lang="nemerle">using System;
using System.Console;
using System.Console;


Line 1,486: Line 1,868:
} while ((!numeric) || (entry != 75000))
} while ((!numeric) || (entry != 75000))
}
}
}</lang>
}</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
options replace format comments java crossref symbols nobinary


Line 1,506: Line 1,888:
end
end
return
return
</syntaxhighlight>
</lang>


=={{header|newLISP}}==
=={{header|newLISP}}==
{{works with|newLISP|9.0}}
{{works with|newLISP|9.0}}
<lang lisp>(print "Enter an integer: ")
<syntaxhighlight 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))</lang>
(set 'y (read-line))</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import rdstdin, strutils
<syntaxhighlight lang="nim">import rdstdin, strutils


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


=={{header|NS-HUBASIC}}==
=={{header|NS-HUBASIC}}==
<lang NS-HUBASIC>10 INPUT "ENTER A STRING: ",STRING$
<syntaxhighlight lang="ns-hubasic">10 INPUT "ENTER A STRING: ",STRING$
20 PRINT "YOU ENTERED ";STRING$;"."
20 PRINT "YOU ENTERED ";STRING$;"."
30 INPUT "ENTER AN INTEGER: ",INTEGER
30 INPUT "ENTER AN INTEGER: ",INTEGER
40 PRINT "YOU ENTERED";INTEGER;"."</lang>
40 PRINT "YOU ENTERED";INTEGER;"."</syntaxhighlight>

=={{header|Nu}}==
<syntaxhighlight lang="nu">
{
String: (input "Enter a string: ")
Number: (input "Enter an integer: ")
}
</syntaxhighlight>
{{out}}
<pre>
Enter a string: Hello world!
Enter an integer: 75000
╭────────┬──────────────╮
│ String │ Hello world! │
│ Number │ 75000 │
╰────────┴──────────────╯
</pre>


=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
{{works with|oo2c}}
{{works with|oo2c}}
<lang oberon2>
<syntaxhighlight lang="oberon2">
MODULE InputText;
MODULE InputText;
IMPORT
IMPORT
Line 1,541: Line 1,940:
Out.String("Enter a string: ");Out.Flush();In.String(str);
Out.String("Enter a string: ");Out.Flush();In.String(str);
END InputText.
END InputText.
</syntaxhighlight>
</lang>


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>
<syntaxhighlight lang="objeck">
use IO;
use IO;


Line 1,558: Line 1,957:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>print_string "Enter a string: ";
<syntaxhighlight lang="ocaml">print_string "Enter a string: ";
let str = read_line () in
let str = read_line () in
print_string "Enter an integer: ";
print_string "Enter an integer: ";
let num = read_int () in
let num = read_int () in
Printf.printf "%s%d\n" str num</lang>
Printf.printf "%s%d\n" str num</syntaxhighlight>


=={{header|Octave}}==
=={{header|Octave}}==


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


Line 1,583: Line 1,982:
disp(s);
disp(s);
disp(i);
disp(i);
disp(ri);</lang>
disp(ri);</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>import: console
<syntaxhighlight lang="oforth">import: console


: testInput{
: testInput{
Line 1,594: Line 1,993:
while (System.Console askln asInteger dup ->n isNull) [ "Not an integer" println ]
while (System.Console askln asInteger dup ->n isNull) [ "Not an integer" println ]


System.Out "Received : " << s << " and " << n << cr ;</lang>
System.Out "Received : " << s << " and " << n << cr ;</syntaxhighlight>


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>declare
<syntaxhighlight lang="oz">declare
StdIn = {New class $ from Open.file Open.text end init(name:stdin)}
StdIn = {New class $ from Open.file Open.text end init(name:stdin)}
StringInput
StringInput
Line 1,610: Line 2,009:
in
in
Num := try {String.toInt Line} catch _ then 0 end
Num := try {String.toInt Line} catch _ then 0 end
end</lang>
end</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>s=input();
<syntaxhighlight lang="parigp">s=input();
n=eval(input());</lang>
n=eval(input());</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==


<lang pascal>program UserInput(input, output);
<syntaxhighlight lang="pascal">program UserInput(input, output);
var i : Integer;
var i : Integer;
s : String;
s : String;
Line 1,626: Line 2,025:
write('Enter a string: ');
write('Enter a string: ');
readln(s)
readln(s)
end.</lang>
end.</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>print "Enter a string: ";
<syntaxhighlight lang="perl">print "Enter a string: ";
my $string = <>;
my $string = <>;
print "Enter an integer: ";
print "Enter an integer: ";
my $integer = <>;</lang>
my $integer = <>;</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(notonline)-->
<lang Phix>?prompt_string("Enter any string:")
<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>
?prompt_number("Enter the number 75000:",{75000,75000})</lang>
<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>
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 1,646: Line 2,047:
75000
75000
</pre>
</pre>

=={{header|Phixmonti}}==
<syntaxhighlight lang="Phixmonti">/# Rosetta Code problem: https://rosettacode.org/wiki/User_input/Text
by Galileo, 10/2022 #/

"Enter any string: " input nl
true while
75000 "Enter the number " over tostr chain ": " chain input
nl tonum over == not
endwhile
drop pstack</syntaxhighlight>
{{out}}
<pre>Enter any string: Hello
Enter the number 75000: 1000
Enter the number 75000: 75000

["Hello", 75000]

=== Press any key to exit ===</pre>


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

=={{header|Picat}}==
<syntaxhighlight lang="picat">main =>
print("Enter a string: "),
String = read_line(),
print("Enter a number: "),
Number = read_int(),
println([string=String,number=Number]).</syntaxhighlight>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(in NIL # Guarantee reading from standard input
<syntaxhighlight lang="picolisp">(in NIL # Guarantee reading from standard input
(let (Str (read) Num (read))
(let (Str (read) Num (read))
(prinl "The string is: \"" Str "\"")
(prinl "The string is: \"" Str "\"")
(prinl "The number is: " Num) ) )</lang>
(prinl "The number is: " Num) ) )</syntaxhighlight>


=={{header|Pike}}==
=={{header|Pike}}==
<lang pike>int main(){
<syntaxhighlight lang="pike">int main(){
write("Enter a String: ");
write("Enter a String: ");
string str = Stdio.stdin->gets();
string str = Stdio.stdin->gets();
write("Enter 75000: ");
write("Enter 75000: ");
int num = Stdio.stdin->gets();
int num = Stdio.stdin->gets();
}</lang>
}</syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang PL/I>declare s character (100) varying;
<syntaxhighlight lang="pl/i">declare s character (100) varying;
declare k fixed decimal (15);
declare k fixed decimal (15);


Line 1,679: Line 2,107:
get list (k);
get list (k);
put skip list (k);
put skip list (k);
put skip list ('Thanks');</lang>
put skip list ('Thanks');</syntaxhighlight>

=={{header|Plain English}}==
<syntaxhighlight lang="plainenglish">To run:
Start up.
Demonstrate input.
Wait for the escape key.
Shut down.
To demonstrate input:
Write "Enter a string: " to the console without advancing.
Read a string from the console.
Write "Enter a number: " to the console without advancing.
Read a number from the console.
\Now show the input values
Write "The string: " then the string to the console.
Write "The number: " then the number to the console.</syntaxhighlight>
A sample run of the program:
{{out}}
<pre>
Enter a string: abc
Enter a number: 123
The string: abc
The number: 123
</pre>


=={{header|Pop11}}==
=={{header|Pop11}}==
<lang pop11>;;; Setup item reader
<syntaxhighlight lang="pop11">;;; Setup item reader
lvars itemrep = incharitem(charin);
lvars itemrep = incharitem(charin);
lvars s, c, j = 0;
lvars s, c, j = 0;
Line 1,690: Line 2,142:
consstring(j) -> s;
consstring(j) -> s;
;;; read the integer
;;; read the integer
lvars i = itemrep();</lang>
lvars i = itemrep();</syntaxhighlight>


=={{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"):
<syntaxhighlight 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</syntaxhighlight>


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:
<syntaxhighlight lang="postscript">%if the read was successful, convert the string to integer:
{cvi} if</lang>
{cvi} if</syntaxhighlight>


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 1,710: Line 2,162:
=={{header|PowerShell}}==
=={{header|PowerShell}}==


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


=={{header|PureBasic}}==
=={{header|PureBasic}}==


<lang PureBasic>If OpenConsole()
<syntaxhighlight lang="purebasic">If OpenConsole()
; Declare a string and a integer to be used
; Declare a string and a integer to be used
Define txt.s, num.i
Define txt.s, num.i
Line 1,730: Line 2,182:
Print("You made it!")
Print("You made it!")
Delay(3000): CloseConsole()
Delay(3000): CloseConsole()
EndIf</lang>
EndIf</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
===Input a string===
===Input a string===
<lang python> string = raw_input("Input a string: ")</lang>
<syntaxhighlight lang="python"> string = raw_input("Input a string: ")</syntaxhighlight>
In Python 3.0, raw_input will be renamed to input(). The Python 3.0 equivalent would be
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>
<syntaxhighlight lang="python"> string = input("Input a string: ")</syntaxhighlight>
===Input a number===
===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.
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>
<syntaxhighlight lang="python"> number = input("Input a number: ") # Deprecated, please don't use.</syntaxhighlight>
Python 3.0 equivalent:
Python 3.0 equivalent:
<lang python> number = eval(input("Input a number: ")) # Evil, please don't use.</lang>
<syntaxhighlight lang="python"> number = eval(input("Input a number: ")) # Evil, please don't use.</syntaxhighlight>
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.
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>
<syntaxhighlight lang="python"> number = float(raw_input("Input a number: "))</syntaxhighlight>
Python 3.0 equivalent:
Python 3.0 equivalent:
<lang python> number = float(input("Input a number: "))</lang>
<syntaxhighlight lang="python"> number = float(input("Input a number: "))</syntaxhighlight>
float may be replaced by any numeric type, such as int, complex, or decimal.Decimal. Each one varies in expected input.
float may be replaced by any numeric type, such as int, complex, or decimal.Decimal. Each one varies in expected input.

=={{header|Quackery}}==

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.

<syntaxhighlight lang="quackery">$ "Please enter a string: " input
say 'You entered: "' echo$ say '"' cr cr
$ "Please enter an integer: " input
trim reverse trim reverse
$->n iff
[ say "You entered: " echo cr ]
else
[ say "That was not an integer." cr
drop ]</syntaxhighlight>

{{out}}

<pre>Please enter a string: 3-ply sisal twine
You entered: "3-ply sisal twine"

Please enter an integer: 75000
You entered: 75000
</pre>


=={{header|R}}==
=={{header|R}}==
{{works with|R|2.81}}
{{works with|R|2.81}}


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


=={{header|Racket}}==
=={{header|Racket}}==


<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
#lang racket
(printf "Input a string: ")
(printf "Input a string: ")
Line 1,772: Line 2,248:
(unless (number? n) (error "I said a number!"))
(unless (number? n) (error "I said a number!"))
(printf "You entered: ~a\n" n)
(printf "You entered: ~a\n" n)
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
<lang perl6>my $str = prompt("Enter a string: ");
<syntaxhighlight lang="raku" line>my $str = prompt("Enter a string: ");
my $int = prompt("Enter a integer: ");</lang>
my $int = prompt("Enter a integer: ");</syntaxhighlight>


=={{header|Rascal}}==
=={{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:
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;
<syntaxhighlight lang="rascal">import util::IDE;
public void InputConsole(){
public void InputConsole(){
x = "";
x = "";
Line 1,788: Line 2,264:
str (str inp) {x = "<inp == "75000" ? "You entered 75000" : "You entered a string">";
str (str inp) {x = "<inp == "75000" ? "You entered 75000" : "You entered a string">";
return "<x>\n<inp>\nInput\>";});
return "<x>\n<inp>\nInput\>";});
}</lang>
}</syntaxhighlight>
Which has as output:
Which has as output:


Line 1,796: Line 2,272:


=={{header|Raven}}==
=={{header|Raven}}==
<lang raven>'Input a string: ' print expect as str
<syntaxhighlight 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</syntaxhighlight>


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang REBOL>REBOL [
<syntaxhighlight lang="rebol">REBOL [
Title: "Textual User Input"
Title: "Textual User Input"
URL: http://rosettacode.org/wiki/User_Input_-_text
URL: http://rosettacode.org/wiki/User_Input_-_text
Line 1,826: Line 2,302:
; It always pays to be polite...
; It always pays to be polite...


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


Output:
Output:
Line 1,842: Line 2,318:


=={{header|Red}}==
=={{header|Red}}==
<lang Red>n: ask "Please enter # 75000: " str: ask "Please enter any string: "</lang>
<syntaxhighlight lang="red">n: ask "Please enter # 75000: " str: ask "Please enter any string: "</syntaxhighlight>


=={{header|Retro}}==
=={{header|Retro}}==
<lang Retro>:example ("-)
<syntaxhighlight lang="retro">:example ("-)
'Enter_a_string:_ s:put s:get s:keep
'Enter_a_string:_ s:put s:get s:keep
[ 'Enter_75000:_ s:put s:get-word s:to-number nl #75000 eq? ] until
[ 'Enter_75000:_ s:put s:get-word s:to-number nl #75000 eq? ] until
'Your_string_was:_'%s'\n s:format s:put ;</lang>
'Your_string_was:_'%s'\n s:format s:put ;</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
Line 1,863: Line 2,339:
do until userNumber==75000
do until userNumber==75000


<lang rexx>/*REXX program prompts & reads/obtains a string, and also the number 75000 from terminal*/
<syntaxhighlight lang="rexx">/*REXX program prompts & reads/obtains a string, and also the number 75000 from terminal*/
say 'Please enter a string:' /*issue a prompt message to the term. */
say 'Please enter a string:' /*issue a prompt message to the term. */
parse pull userString /*the (char) string can be any length. */
parse pull userString /*the (char) string can be any length. */
Line 1,872: Line 2,348:
parse pull userNumber /*obtain the user text from terminal. */
parse pull userNumber /*obtain the user text from terminal. */
end /*until*/ /*check if the response is legitimate. */
end /*until*/ /*check if the response is legitimate. */
/*stick a fork in it, we're all done. */</lang>
/*stick a fork in it, we're all done. */</syntaxhighlight>


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
see "Enter a string : " give s
see "Enter a string : " give s
see "Enter an integer : " give i
see "Enter an integer : " give i
see "String = " + s + nl
see "String = " + s + nl
see "Integer = " + i + nl
see "Integer = " + i + nl
</syntaxhighlight>
</lang>


=={{header|Robotic}}==
=={{header|Robotic}}==
<lang robotic>
<syntaxhighlight lang="robotic">
input string "Enter string:"
input string "Enter string:"
set "$str" to "input"
set "$str" to "input"
Line 1,892: Line 2,368:
[ "&number&"
[ "&number&"
end
end
</syntaxhighlight>
</lang>


To ensure that a specific number must be entered, just create a loop around the second input function:
To ensure that a specific number must be entered, just create a loop around the second input function:
<lang robotic>
<syntaxhighlight lang="robotic">
input string "Enter string:"
input string "Enter string:"
set "$str" to "input"
set "$str" to "input"
Line 1,906: Line 2,382:
[ "&number&"
[ "&number&"
end
end
</syntaxhighlight>
</lang>

=={{header|RPL}}==
≪ <span style="color:red">"Enter text" { "" 𝛼 }</span> INPUT <span style="color:grey">@ Set keyboard alpha mode</span>
<span style="color:red">75000</span> → string n75000
≪ '''DO'''
<span style="color:red">"Enter number "</span> n + <span style="color:red">""</span> INPUT
'''UNTIL''' n →STR == '''END'''
string number
≫ ≫ '<span style="color:blue">TASK</span>' STO


=={{header|Ruby}}==
=={{header|Ruby}}==
{{works with|Ruby|1.8.4}}
{{works with|Ruby|1.8.4}}
<lang ruby>print "Enter a string: "
<syntaxhighlight lang="ruby">print "Enter a string: "
s = gets
s = gets
printf "Enter an integer: "
printf "Enter an integer: "
Line 1,918: Line 2,403:
puts "String = #{s}"
puts "String = #{s}"
puts "Integer = #{i}"
puts "Integer = #{i}"
puts "Float = #{f}"</lang>
puts "Float = #{f}"</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
This program shows all the proper error handling.
This program shows all the proper error handling.
<lang rust>use std::io::{self, Write};
<syntaxhighlight lang="rust">use std::io::{self, Write};
use std::fmt::Display;
use std::fmt::Display;
use std::process;
use std::process;
Line 1,953: Line 2,438:
let _ = writeln!(&mut io::stderr(), "Error: {}", msg);
let _ = writeln!(&mut io::stderr(), "Error: {}", msg);
process::exit(code)
process::exit(code)
}</lang>
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>print("Enter a number: ")
<syntaxhighlight lang="scala">print("Enter a number: ")
val i=Console.readLong // Task says to enter 75000
val i=Console.readLong // Task says to enter 75000
print("Enter a string: ")
print("Enter a string: ")
val s=Console.readLine</lang>
val s=Console.readLine</syntaxhighlight>


=={{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))
<syntaxhighlight 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)</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";


const proc: main is func
const proc: main is func
Line 1,980: Line 2,465:
write("Enter a string: ");
write("Enter a string: ");
readln(string_input);
readln(string_input);
end func;</lang>
end func;</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
Using the '''read(Type)''' built-in function:
Using the '''read(Type)''' built-in function:
<lang ruby>var s = read(String);
<syntaxhighlight lang="ruby">var s = read(String);
var i = read(Number); # auto-conversion to a number</lang>
var i = read(Number); # auto-conversion to a number</syntaxhighlight>


or using the '''Sys.readln(msg)''' method:
or using the '''Sys.readln(msg)''' method:
<lang ruby>var s = Sys.readln("Enter a string: ");
<syntaxhighlight lang="ruby">var s = Sys.readln("Enter a string: ");
var i = Sys.readln("Enter a number: ").to_i;</lang>
var i = Sys.readln("Enter a number: ").to_i;</syntaxhighlight>


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


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
<lang smalltalk>'Enter a number: ' display.
<syntaxhighlight lang="smalltalk">'Enter a number: ' display.
a := stdin nextLine asInteger.
a := stdin nextLine asInteger.


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


=={{header|smart BASIC}}==
=={{header|smart BASIC}}==
Line 2,011: Line 2,496:
'''NOTE:''' The INPUT command uses a colon (:) as opposed to a comma (,) or semi-conlon (;) like other forms of BASIC.
'''NOTE:''' The INPUT command uses a colon (:) as opposed to a comma (,) or semi-conlon (;) like other forms of BASIC.


<lang qbasic>INPUT "Enter a string.":a$
<syntaxhighlight lang="qbasic">INPUT "Enter a string.":a$
INPUT "Enter the value 75000.":n</lang>
INPUT "Enter the value 75000.":n</syntaxhighlight>


=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==
<lang snobol4> output = "Enter a string:"
<syntaxhighlight lang="snobol4"> output = "Enter a string:"
str = trim(input)
str = trim(input)
output = "Enter an integer:"
output = "Enter an integer:"
int = trim(input)
int = trim(input)
output = "String: " str " Integer: " int
output = "String: " str " Integer: " int
end</lang>
end</syntaxhighlight>


=={{header|SPL}}==
=={{header|SPL}}==
In SPL all console input is text, so number should be converted from text using #.val function.
In SPL all console input is text, so number should be converted from text using #.val function.
<lang spl>text = #.input("Input a string")
<syntaxhighlight lang="spl">text = #.input("Input a string")
number = #.val(#.input("Input a number"))</lang>
number = #.val(#.input("Input a number"))</syntaxhighlight>

=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "get_string" )
@( description, "Input a string and the integer 75000 from the text console." )
@( see_also, "https://rosettacode.org/wiki/User_input/Text" )
@( author, "Ken O. Burtch" );
pragma license( unrestricted );

pragma restriction( no_external_commands );

procedure get_string is
s : unbounded_string;
i : integer;
begin
s := get_line;
i := integer( numerics.value( get_line ) );
? s @ i;
exception when others =>
put_line( standard_error, "the value is not valid" );
end get_string;</syntaxhighlight>
As a unstructured script and no exception handling.
<syntaxhighlight lang="ada">
s := get_line;
i := numerics.value( get_line );
? s @ i;</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang sml>print "Enter a string: ";
<syntaxhighlight lang="sml">print "Enter a string: ";
let val str = valOf (TextIO.inputLine TextIO.stdIn) in (* note: this keeps the trailing newline *)
let val str = valOf (TextIO.inputLine TextIO.stdIn) in (* note: this keeps the trailing newline *)
print "Enter an integer: ";
print "Enter an integer: ";
Line 2,034: Line 2,547:
print (str ^ Int.toString num ^ "\n")
print (str ^ Int.toString num ^ "\n")
end
end
end</lang>
end</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
{{works with|Swift|2.x+}}
{{works with|Swift|2.x+}}
<lang swift>print("Enter a string: ", terminator: "")
<syntaxhighlight lang="swift">print("Enter a string: ", terminator: "")
if let str = readLine() {
if let str = readLine() {
print(str)
print(str)
}</lang>
}</syntaxhighlight>
{{works with|Swift|5.x+}}
<syntaxhighlight lang="swift">print("Enter a string: ", terminator: "")
guard let str = readLine() else {
fatalError("Nothing read!")
}
print(str)
print("Enter a number: ", terminator: "")
guard let nstr = readLine(), let num = Int(nstr) else {
fatalError("Not a number!")
}
print(num)</syntaxhighlight>


=={{header|Tcl}}==
=={{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:
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]
<syntaxhighlight lang="tcl">set str [gets stdin]
set num [gets stdin]</lang>
set num [gets stdin]</syntaxhighlight>
possibly followed by something like
possibly followed by something like
<lang tcl>if {![string is integer -strict $num]} then { ...do something here...}</lang>
<syntaxhighlight lang="tcl">if {![string is integer -strict $num]} then { ...do something here...}</syntaxhighlight>


If the requirement is to prompt until the user enters the integer 75000, then:
If the requirement is to prompt until the user enters the integer 75000, then:
<lang tcl>set input 0
<syntaxhighlight lang="tcl">set input 0
while {$input != 75000} {
while {$input != 75000} {
puts -nonewline "enter the number '75000': "
puts -nonewline "enter the number '75000': "
flush stdout
flush stdout
set input [gets stdin]
set input [gets stdin]
}</lang>
}</syntaxhighlight>


Of course, it's nicer to wrap the primitives in a procedure:
Of course, it's nicer to wrap the primitives in a procedure:
<lang tcl>proc question {var message} {
<syntaxhighlight lang="tcl">proc question {var message} {
upvar 1 $var v
upvar 1 $var v
puts -nonewline "$message: "
puts -nonewline "$message: "
Line 2,067: Line 2,591:
question name "What is your name"
question name "What is your name"
question task "What is your quest"
question task "What is your quest"
question doom "What is the air-speed velocity of an unladen swallow"</lang>
question doom "What is the air-speed velocity of an unladen swallow"</syntaxhighlight>


=={{header|TI-83 BASIC}}==
=={{header|TI-83 BASIC}}==
Line 2,073: Line 2,597:
This program leaves the string in String1, and the integer in variable "i".
This program leaves the string in String1, and the integer in variable "i".


<lang ti83b>
<syntaxhighlight lang="ti83b">
:Input "Enter a string:",Str1
:Input "Enter a string:",Str1
:Prompt i
:Prompt i
Line 2,080: Line 2,604:
:Else
:Else
:Stop
:Stop
</syntaxhighlight>
</lang>


=={{header|TI-89 BASIC}}==
=={{header|TI-89 BASIC}}==
Line 2,086: Line 2,610:
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
<syntaxhighlight lang="ti89b">Prgm
InputStr "Enter a string", s
InputStr "Enter a string", s
Loop
Loop
Line 2,096: Line 2,620:
EndIf
EndIf
EndLoop
EndLoop
EndPrgm</lang>
EndPrgm</syntaxhighlight>


=={{header|Toka}}==
=={{header|Toka}}==
<lang toka>needs readline
<syntaxhighlight 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</lang>
the-number . cr</syntaxhighlight>


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
$$ MODE TUSCRIPT
LOOP
LOOP
Line 2,120: Line 2,644:
ENDIF
ENDIF
ENDLOOP
ENDLOOP
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 2,133: Line 2,657:
=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
{{works with|Bourne Shell}}
{{works with|Bourne Shell}}
<lang bash>#!/bin/sh
<syntaxhighlight lang="bash">#!/bin/sh


read string
read string
read integer
read integer
read -p 'Enter a number: ' number
read -p 'Enter a number: ' number
echo "The number is $number"</lang>
echo "The number is $number"</syntaxhighlight>


=={{header|Ursa}}==
=={{header|Ursa}}==
<lang ursa>#
<syntaxhighlight lang="ursa">#
# user input
# user input
#
#
Line 2,154: Line 2,678:
set i (in int console)
set i (in int console)


out "you entered " str " and " i endl console</lang>
out "you entered " str " and " i endl console</syntaxhighlight>


=={{header|VBA}}==
=={{header|VBA}}==
<lang vb>Public Sub text()
<syntaxhighlight lang="vb">Public Sub text()
Debug.Print InputBox("Input a string")
Debug.Print InputBox("Input a string")
Debug.Print InputBox("Input the integer 75000", "Input an integer", 75000, Context = "Long")
Debug.Print InputBox("Input the integer 75000", "Input an integer", 75000, Context = "Long")
End Sub</lang>
End Sub</syntaxhighlight>


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


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
Line 2,172: Line 2,696:


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


===Input an Integer With Error Handling===
===Input an Integer With Error Handling===
<lang vbnet>Dim i As Integer
<syntaxhighlight lang="vbnet">Dim i As Integer
Dim iString As String
Dim iString As String
Console.WriteLine("Enter an Integer")
Console.WriteLine("Enter an Integer")
Line 2,185: Line 2,709:
Catch ex As Exception
Catch ex As Exception
Console.WriteLine("This is not an Integer")
Console.WriteLine("This is not an Integer")
End Try</lang>
End Try</syntaxhighlight>


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

=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">import os

fn main() {
s := os.input('Enter string').int()
if s == 75000 {
println('good')
} else {
println('bad')
}
}</syntaxhighlight>

==Input conversion with Error Handling==
<syntaxhighlight lang="text">import os
import strconv

fn main() {
s := strconv.atoi(os.input('Enter string')) ?
if s == 75000 {
println('good')
} else {
println('bad $s')
}
}</syntaxhighlight>


=={{header|Wee Basic}}==
=={{header|Wee Basic}}==
<lang>print 1 "Enter a string."
<syntaxhighlight lang="text">print 1 "Enter a string."
input string$
input string$
print 1 "Enter an integer."
print 1 "Enter an integer."
input integer</lang>
input integer</syntaxhighlight>

=={{header|Wren}}==
<syntaxhighlight lang="wren">import "io" for Stdin, Stdout

var string
while (true) {
System.write("Enter a string : ")
Stdout.flush()
string = Stdin.readLine()
if (string.count == 0) {
System.print("String cannot be empty, try again.")
} else {
break
}
}

var number
while (true) {
System.write("Enter a number : ")
Stdout.flush()
number = Num.fromString(Stdin.readLine())
if (!number || !number.isInteger) {
System.print("Please enter a vaid integer, try again.")
} else {
break
}
}

System.print("\nYou entered:")
System.print(" string: %(string)")
System.print(" number: %(number)")</syntaxhighlight>

{{out}}
<pre>
Enter a string : Rosetta Code
Enter a number : 75000

You entered:
string: Rosetta Code
number: 75000
</pre>


=={{header|XLISP}}==
=={{header|XLISP}}==
<tt>READ-LINE</tt> reads a line of input as a string; <tt>READ</tt> reads an expression, of arbitrary complexity.
<tt>READ-LINE</tt> reads a line of input as a string; <tt>READ</tt> reads an expression, of arbitrary complexity.
<lang scheme>(display "Enter a string: ")
<syntaxhighlight lang="scheme">(display "Enter a string: ")
(define s (read-line))
(define s (read-line))
(display "Yes, ")
(display "Yes, ")
Line 2,215: Line 2,805:
"That is not the integer 75000." )
"That is not the integer 75000." )
(t
(t
"Yes, that is the integer 75000." ) ) )</lang>
"Yes, that is the integer 75000." ) ) )</syntaxhighlight>
{{out}}
{{out}}
<pre>Enter a string: Rosetta Code
<pre>Enter a string: Rosetta Code
Line 2,230: Line 2,820:
place of the Enter key to mark the end of the string.
place of the Enter key to mark the end of the string.


<lang XPL0>string 0; \use zero-terminated strings, instead of MSb terminated
<syntaxhighlight lang="xpl0">string 0; \use zero-terminated strings, instead of MSb terminated
include c:\cxpl\codes;
include c:\cxpl\codes;
int I;
int I;
Line 2,244: Line 2,834:
Text(0, "Howdy "); Text(0, Name); Text(0, "! Now please enter ^"75000^": ");
Text(0, "Howdy "); Text(0, Name); Text(0, "! Now please enter ^"75000^": ");
IntOut(0, IntIn(0)); CrLf(0); \echo the number
IntOut(0, IntIn(0)); CrLf(0); \echo the number
]</lang>
]</syntaxhighlight>


Example output:
Example output:
Line 2,254: Line 2,844:


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


=={{header|ZX Spectrum Basic}}==
=={{header|ZX Spectrum Basic}}==


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


{{omit from|GUISS|We need an application that asks for these}}
{{omit from|GUISS|We need an application that asks for these}}
{{omit from|SQL PL|It does not handle user interaction, only the clients to access database done that}}
{{omit from|SQL PL|It does not handle user interaction, only the clients to access database done that}}

----

Latest revision as of 13:28, 3 March 2024

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

Input a string and the integer   75000   from the text console.

See also: User input/Graphical

11l

V string = input(‘Input a string: ’)
V number = Float(input(‘Input a number: ’))

AArch64 Assembly

Works with: as version Raspberry Pi 3B/4 version Buster 64 bits
//Consts
.equ BUFFERSIZE,   100
.equ STDIN,  0                // linux input console
.equ STDOUT, 1                // linux output console
.equ READ,   63 
.equ WRITE,  64 
.equ EXIT,   93 

.data
enterText:		.asciz "Enter text: "
carriageReturn:  	.asciz "\n"

//Read Buffer
.bss 
buffer:    .skip    BUFFERSIZE

.text
.global _start 

quadEnterText:        	.quad  enterText
quadBuffer:          	.quad  buffer
quadCarriageReturn:	.quad  carriageReturn

writeMessage:
    mov x2,0                   // reset size counter to 0

checkSize:                     // get size of input
    ldrb w1,[x0,x2]            // load char with offset of x2
    add x2,x2,#1               // add 1 char read legnth
    cbz w1,output              // if char found
    b checkSize                // loop

output:
    mov x1,x0                  // move string address into system call func parm
    mov x0,STDOUT              
    mov x8,WRITE               
    svc 0                      // trigger system write
    ret                        


_start:
    //Output enter text
    ldr x0,quadEnterText	// load enter message
    bl writeMessage		// output enter message

    //Read User Input
    mov x0,STDIN           	// linux input console
    ldr x1,quadBuffer      	// load buffer address 
    mov x2,BUFFERSIZE      	// load buffer size 
    mov x8,READ            	// request to read data
    svc 0                  	// trigger system read input

    //Output User Message
    mov x2, #0			// prep end of string
    ldr x1,quadBuffer      	// load buffer address 
    strb w2,[x1, x0]        	// store x2 0 byte at the end of input string, offset x0
    ldr x0,quadBuffer      	// load buffer address 
    bl writeMessage
    
    //Output newline
    ldr x0,quadCarriageReturn   
    bl writeMessage

    //End Program
    mov x0, #0             	// return code
    mov x8, #EXIT          	// request to exit program
    svc 0                 	// trigger end of program

Action!

INCLUDE "H6:REALMATH.ACT"

PROC Main()
  CHAR ARRAY sUser(255)
  REAL r75000,rUser

  Put(125) PutE() ;clear the screen
  ValR("75000",r75000)

  Print("Please enter a text: ")
  InputS(sUser)

  DO
    Print("Please enter number ")
    PrintR(r75000) Print(": ")
    InputR(rUser)
  UNTIL RealEqual(rUser,r75000)
  OD

  PutE()
  Print("Text: ") PrintE(sUser)
  Print("Number: ") PrintRE(rUser)
RETURN
Output:

Screenshot from Atari 8-bit computer

Please enter a text: Atari 130XE
Please enter number 75000: 123
Please enter number 75000: 76000
Please enter number 75000: 75000

Text: Atari 130XE
Number: 75000

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;

Another:

with Ada.Text_IO, Ada.Integer_Text_IO;

procedure User_Input is
   I : Integer;
begin
   Ada.Text_IO.Put ("Enter a string: ");
   declare
      S : String := Ada.Text_IO.Get_Line;
   begin
      Ada.Text_IO.Put_Line (S);
   end;
   Ada.Text_IO.Put ("Enter an integer: ");
   Ada.Integer_Text_IO.Get(I);
   Ada.Text_IO.Put_Line (Integer'Image(I));
end User_Input;

Unbounded IO:

with
  Ada.Text_IO,
  Ada.Integer_Text_IO,
  Ada.Strings.Unbounded,
  Ada.Text_IO.Unbounded_IO;

procedure User_Input2 is
   S : Ada.Strings.Unbounded.Unbounded_String;
   I : Integer;
begin
   Ada.Text_IO.Put("Enter a string: ");
   S := Ada.Strings.Unbounded.To_Unbounded_String(Ada.Text_IO.Get_Line);
   Ada.Text_IO.Put_Line(Ada.Strings.Unbounded.To_String(S));
   Ada.Text_IO.Unbounded_IO.Put_Line(S);
   Ada.Text_IO.Put("Enter an integer: ");
   Ada.Integer_Text_IO.Get(I);
   Ada.Text_IO.Put_Line(Integer'Image(I));
end User_Input2;

ALGOL 68

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

ALGOL W

begin
    string(80) s;
    integer    n;
    write( "Enter a string  > " );
    read( s );
    write( "Enter an integer> " );
    read( n )
end.

Amazing Hopper

Version: hopper-FLOW!

#include <flow.h>

#import lib/input.bas.lib
#include include/flow-input.h

DEF-MAIN(argv,argc)
   CLR-SCR
   MSET( número, cadena )
   LOCATE(2,2), PRNL( "Input an string : "), LOC-COL(20), LET( cadena := READ-STRING( cadena ) )
   LOCATE(3,2), PRNL( "Input an integer: "), LOC-COL(20), LET( número := INT( VAL(READ-NUMBER( número )) ) )
   LOCATE(5,2), PRNL( cadena, "\n ",número ) 
END
Output:
 Input an string : Juanita Pérez 
 Input an integer: 75000.789 

 Juanita Pérez
 75000

APL

str
int

ARM Assembly

Works with: as version Raspberry Pi
/* ARM assembly Raspberry PI  */
/*  program inputText.s   */

/* Constantes    */
.equ BUFFERSIZE,   100
.equ STDIN,  0     @ Linux input console
.equ STDOUT, 1     @ Linux output console
.equ EXIT,   1     @ Linux syscall
.equ READ,   3     @ Linux syscall
.equ WRITE,  4     @ Linux syscall
/* Initialized data */
.data
szMessDeb: .asciz "Enter text : \n"
szMessNum: .asciz "Enter number : \n"
szCarriageReturn:  .asciz "\n"

/* UnInitialized data */
.bss 
sBuffer:    .skip    BUFFERSIZE

/*  code section */
.text
.global main 
main:                /* entry of program  */
    push {fp,lr}    /* saves 2 registers */
    ldr r0,iAdrszMessDeb
    bl affichageMess
    mov r0,#STDIN         @ Linux input console
    ldr r1,iAdrsBuffer   @ buffer address 
    mov r2,#BUFFERSIZE   @ buffer size 
    mov r7, #READ         @ request to read datas
    swi 0                  @ call system
    ldr r1,iAdrsBuffer    @ buffer address 
    mov r2,#0                @ end of string
    strb r2,[r1,r0]         @ store byte at the end of input string (r0 contains number of characters)

    ldr r0,iAdrsBuffer    @ buffer address 
    bl affichageMess
    ldr r0,iAdrszCarriageReturn   
    bl affichageMess

    ldr r0,iAdrszMessNum
    bl affichageMess
    mov r0,#STDIN         @ Linux input console
    ldr r1,iAdrsBuffer   @ buffer address 
    mov r2,#BUFFERSIZE   @ buffer size 
    mov r7, #READ         @ request to read datas
    swi 0                  @ call system
    ldr r1,iAdrsBuffer    @ buffer address 
    mov r2,#0                @ end of string
    strb r2,[r1,r0]         @ store byte at the end of input string (r0
    @ 
    ldr r0,iAdrsBuffer    @ buffer address
    bl conversionAtoD    @ conversion string in number in r0
    
100:   /* standard end of the program */
    mov r0, #0                  @ return code
    pop {fp,lr}                 @restaur 2 registers
    mov r7, #EXIT              @ request to exit program
    swi 0                       @ perform the system call

iAdrszMessDeb:  .int szMessDeb
iAdrszMessNum: .int  szMessNum
iAdrsBuffer:   .int  sBuffer
iAdrszCarriageReturn:  .int  szCarriageReturn
/******************************************************************/
/*     display text with size calculation                         */ 
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {fp,lr}    			/* save  registres */ 
    push {r0,r1,r2,r7}    		/* save others registers */
    mov r2,#0   				/* counter length */
1:      	/* loop length calculation */
    ldrb r1,[r0,r2]  			/* read octet start position + index */
    cmp r1,#0       			/* if 0 its over */
    addne r2,r2,#1   			/* else add 1 in the length */
    bne 1b          			/* and loop */
                                /* so here r2 contains the length of the message */
    mov r1,r0        			/* address message in r1 */
    mov r0,#STDOUT      		/* code to write to the standard output Linux */
    mov r7, #WRITE             /* code call system "write" */
    swi #0                      /* call systeme */
    pop {r0,r1,r2,r7}     		/* restaur others registers */
    pop {fp,lr}    				/* restaur des  2 registres */ 
    bx lr	        			/* return  */

/******************************************************************/
/*     Convert a string to a number stored in a registry          */ 
/******************************************************************/
/* r0 contains the address of the area terminated by 0 or 0A */
/* r0 returns a number                           */
conversionAtoD:
    push {fp,lr}         @ save 2 registers 
    push {r1-r7}         @ save others registers 
    mov r1,#0
    mov r2,#10           @ factor 
    mov r3,#0            @ counter 
    mov r4,r0            @ save address string -> r4 
    mov r6,#0            @ positive sign by default 
    mov r0,#0            @ initialization to 0 
1:     /* early space elimination loop */
    ldrb r5,[r4,r3]     @ loading in r5 of the byte located at the beginning + the position 
    cmp r5,#0            @ end of string -> end routine
    beq 100f
    cmp r5,#0x0A        @ end of string -> end routine
    beq 100f
    cmp r5,#' '          @ space ? 
    addeq r3,r3,#1      @ yes we loop by moving one byte 
    beq 1b
    cmp r5,#'-'          @ first character is -    
    moveq r6,#1         @  1 -> r6
    beq 3f              @ then move on to the next position 
2:   /* beginning of digit processing loop */
    cmp r5,#'0'          @ character is not a number 
    blt 3f
    cmp r5,#'9'          @ character is not a number
    bgt 3f
    /* character is a number */
    sub r5,#48
    ldr r1,iMaxi       @ check the overflow of the register    
    cmp r0,r1
    bgt 99f            @ overflow error
    mul r0,r2,r0         @ multiply par factor 10 
    add r0,r5            @ add to  r0 
3:
    add r3,r3,#1         @ advance to the next position 
    ldrb r5,[r4,r3]     @ load byte 
    cmp r5,#0            @ end of string -> end routine
    beq 4f
    cmp r5,#0x0A            @ end of string -> end routine
    beq 4f
    b 2b                 @ loop 
4:
    cmp r6,#1            @ test r6 for sign 
    moveq r1,#-1
    muleq r0,r1,r0       @ if negatif, multiply par -1 
    b 100f
99:  /* overflow error */
    ldr r0,=szMessErrDep
    bl   affichageMess
    mov r0,#0      @ return  zero  if error
100:
    pop {r1-r7}          @ restaur other registers 
    pop {fp,lr}          @ restaur   2 registers 
    bx lr                 @return procedure 
/* constante program */	
iMaxi: .int 1073741824	
szMessErrDep:  .asciz  "Too large: overflow 32 bits.\n"

Arturo

str: input "Enter a string: "
num: to :integer input "Enter an integer: "

print ["Got:" str "," num]
Output:
Enter a string: hello world
Enter an integer: 1986
Got: hello world , 1986

AutoHotkey

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

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

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

Axe

Since integers in Axe are two bytes, 75000 exceeds the maximum integer limit (65535). The task has been adjusted accordingly so the integer must be 7500 instead.

In this implementation, the number displayed is effectively the number entered modulo 65536.

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 this table of tokens and their codes for reference.

Disp "String:"
input→A
length(A)→L

.Copy the string to a safe location
Copy(A,L₁,L)

.Display the string
Disp "You entered:",i
For(I,0,L-1)
 Disp {L₁+I}►Char
End
Disp i

Disp "Integer:",i
input→B
length(B)→L

.Parse the string and convert to an integer
0→C
For(I,0,L-1)
 {B+I}-'0'→N
 If N>10
  .Error checking
  Disp "Not a number",i
  Return
 End
 C*10+N→C
End

.Display and check the integer
Disp "You entered:",i,C►Dec,i
If C≠7500
Disp "That isn't 7500"
End

BabyCobol

      * NB: whitespace insignificance and case insensitivity
      * are used in the field name.
       IDENTIFICATION DIVISION.
           PROGRAM-ID. USER INPUT.
       DATA DIVISION.
       01 HUNDRED CHAR STRING PICTURE IS X(100).
       01 FIVE DIGIT NUMBER PICTURE IS 9(5).
       PROCEDURE DIVISION.
           DISPLAY "Enter a string of appropriate length: " WITH NO ADVANCING
           ACCEPT HundredChar String.
           DISPLAY "Enter a number (preferably 75000): " WITH NO ADVANCING
           ACCEPT FiveDigit Number.

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.

INPUT "Enter a string"; s$
INPUT "Enter a number: ", i%

Output (QBasic):

Enter a string? foo
Enter a number: 1

Applesoft BASIC

10 INPUT "ENTER A STRING: "; S$
20 INPUT "ENTER A NUMBER: "; I : I = INT(I)

Commodore BASIC

When using the prompt feature of the INPUT command, the string literal must be followed by a semicolon and then the string variable, or else a ?SYNTAX ERROR will occur. The question mark prompt is always presented with the INPUT command. Any other behavior would have to come from a user-built routine using the GET command.

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."
30 input "will you please type the number 75000";nn
40 if nn<>75000 then print "i'm sorry, that's not right.":goto 30
50 print "thank you.":print "you provided the following values:"
60 print a$
70 print nn
80 end

Output

READY.
RUN
WHAT IS A WORD I SHOULD REMEMBER? PANCAKE
THANK YOU.
WILL YOU PLEASE TYPE THE NUMBER 75000? NO.
?REDO FROM START
WILL YOU PLEASE TYPE THE NUMBER 75000? 848
I'M SORRY, THAT'S NOT RIGHT.
WILL YOU PLEASE TYPE THE NUMBER 75000? 75000
THANK YOU.
YOU PROVIDED THE FOLLOWING VALUES:
PANCAKE
 75000

READY.
█

IS-BASIC

100 INPUT PROMPT "Enter a number: ":NUM
110 INPUT PROMPT "Enter a string: ":ST$

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.

Input "Enter text and a number", s$, l&
Print s$
Print l&

BASIC256

input string "Please enter a string: ", s
do
    input "Please enter 75000   : ", i
until i = 75000
print
print s, i

Run BASIC

input "Please enter a string: "; s$
while i <> 75000
    input "Please enter 75000   : "; i
wend
print
print s$; chr$(9); i

True BASIC

Works with: QBasic
PRINT "Please enter a string";
INPUT s$
DO
   PRINT "Please enter 75000   ";
   INPUT i
LOOP Until i = 75000
PRINT
PRINT s$, i
END

Yabasic

input "Please enter a string: " s$
repeat
    input "Please enter 75000   : " i
until i = 75000
print
print s$, chr$(9), i

Sinclair ZX81 BASIC

10 PRINT "ENTER A STRING"
20 INPUT S$
30 PRINT "YOU ENTERED: ";S$
40 PRINT "NOW ENTER THE NUMBER 75000"
50 INPUT N
60 IF N=75000 THEN STOP
70 PRINT "NO, ";
80 GOTO 40

Batch File

@echo off
set /p var=
echo %var% 75000

BBC BASIC

      INPUT LINE "Enter a string: " string$
      INPUT "Enter a number: " number
      
      PRINT "String = """ string$ """"
      PRINT "Number = " ; number

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: "
 ^,_ & @

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)
);
{?} !doit
Enter a string
abacus
Enter a number
75000h
I said:"a number"!
Enter a number
75000
mystring is abacus
mynumber is 75000

C

#include <stdio.h>
#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;
}

Library: Gadget

#include <gadget/gadget.h>

LIB_GADGET_START

Main
   Cls;
   
   String text;
   int number=0;
   
   At 5,5;  Print "Enter text   : ";
   Atrow 7; Print "Enter ‘75000’: ";
   Atcol 20;
   
   Atrow 5; Fn_let(text, Input ( text, 30 ) );   
   Free secure text;
   
   Atrow 7; Stack{ 
               while (number!=75000 )
                   /*into stack, Input() not need var*/
                   number = Str2int( Input ( NULL, 6 ) );
            }Stack_off;

   Prnl;
End
Output:
$ ./tests/input_cons




    Enter text   : Juanita la mañosa 

    Enter ‘75000’: 75000 
$ 

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();
        }
    }
}

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.

Ceylon

shared void run() {
	print("enter any text here");
	value text = process.readLine();
	print(text);
	print("enter the number 75000 here");
	if (is Integer number = Integer.parse(process.readLine() else "")) {
		print("``number == 75k then number else "close enough"``");
	}
	else {
		print("That was not a number per se.");
	}
}

Clojure

(import '(java.util Scanner))
(def scan (Scanner. *in*))
(def s (.nextLine scan))
(def n (.nextInt scan))

COBOL

Works with: OpenCOBOL
       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
       .

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.")))

Crystal

puts "You entered: #{gets}"

begin
  puts "You entered: #{gets.not_nil!.chomp.to_i}"
rescue ex
  puts ex
end

Example with valid input:

Hello
You entered: Hello
75000
You entered: 75000

Example with invalid input:

Hello
You entered: Hello
Goodbye
Invalid Int32: Goodbye

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, "'");
}

Dart

import 'dart:io' show stdout, stdin;

main() {
	stdout.write('Enter a string: ');
	final string_input = stdin.readLineSync();

	int number_input;	

	do {
		stdout.write('Enter the number 75000: ');
		var number_input_string = stdin.readLineSync();

		try {
			number_input = int.parse(number_input_string);
			if (number_input != 75000)
				stdout.writeln('$number_input is not 75000!');
		} on FormatException {
			stdout.writeln('$number_input_string is not a valid number!');
		} catch ( e ) {
			stdout.writeln(e);
		}

	} while ( number_input != 75000 );

	stdout.writeln('input: $string_input\nnumber: $number_input');
}

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.

Déjà Vu

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

EasyLang

write "Enter a string: "
a$ = input
print ""
repeat
  write "Enter the number 75000: "
  h = number input
  print ""
  until h = 75000
.
print a$ & " " & h

Elena

ELENA 6.x :

import extensions;
 
public program()
{
    var num := new Integer();
    console.write("Enter an integer: ").loadLineTo(num);
 
    var word := console.write("Enter a String: ").readLine()
}

Elixir

a = IO.gets("Enter a string: ")      |> String.strip 
b = IO.gets("Enter an integer: ")    |> String.strip |> String.to_integer
f = IO.gets("Enter a real number: ") |> String.strip |> String.to_float
IO.puts "String  = #{a}"
IO.puts "Integer = #{b}"
IO.puts "Float   = #{f}"

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: ").

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)

F#

open System

let ask_for_input s =
    printf "%s (End with Return): " s
    Console.ReadLine()

[<EntryPoint>]
let main argv = 
    ask_for_input "Input a string" |> ignore
    ask_for_input "Enter the number 75000" |> ignore
    0

Factor

"Enter a string: " write
readln
"Enter a number: " write
readln string>number

Falcon

printl("Enter a string:")
str = input()
printl("Enter a number:")
n = int(input())

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;!.

Fantom

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

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"))
  }
}

Forth

Input a string

: INPUT$ ( n -- addr n )
   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.

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

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

FreeBASIC

' FB 1.05.0 Win64

Dim s As String
Dim i AS Integer
Input "Please enter a string : "; s
Do
  Input "Please enter 75000    : "; i
Loop Until i = 75000
Print
Print s, i
Sleep

Sample input/output

Output:
Please enter a string : ? Rosetta
Please enter 75000    : ? 70000
Please enter 75000    : ? 75000

Rosetta        75000

Frink

s = input["Enter a string: "]
i = parseInt[input["Enter an integer: "]]

GDScript

Works with: Godot version 4.0

Run with godot --headless --script <file>

extends MainLoop

func _process(_delta: float) -> bool:
	printraw("Input a string: ")
	var read_line := OS.read_string_from_stdin() # Mote that this retains the newline.

	printraw("Input an integer: ")
	var read_integer := int(OS.read_string_from_stdin())

	print("read_line = %s" % read_line.trim_suffix("\n"))
	print("read_integer = %d" % read_integer)

	return true # Exit instead of looping

Go

Go has C-like Scan and Scanf functions for quick and dirty input:

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")
    }
}

Code below allows much more control over interaction and error checking.

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")
}

Groovy

word = System.in.readLine()
num = System.in.readLine().toInteger()

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.

hexiscript

print "Enter a string: "
let s scan str
print "Enter a number: "
let n scan int

HolyC

U8 *s;
s = GetStr("Enter a string: ");

U32 *n;
do {
  n = GetStr("Enter 75000: ");
} while(Str2I64(n) != 75000);

Print("Your string: %s\n", s);
Print("75000: %d\n", Str2I64(n));

Icon and Unicon

The following works in both Icon and Unicon:

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

Io

string := File clone standardInput readLine("Enter a string: ")
integer := File clone standardInput readLine("Enter 75000: ") asNumber

J

Solution

   require 'misc'            NB. load system script
   prompt 'Enter string: '
   0".prompt 'Enter an integer: '

Note that require'misc' is old - efforts to optimize by loading misc utilities in a fine grained fashion mean that currently (J 805) that should be require'general/misc/prompt' and the older form fails with an error to call attention to this issue.

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 Code75000
└──────────────────┴─────┘

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());
    }
}

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();
    }
}

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() );
}

Joy

"Enter a string: " putchars
stdin fgets
"Enter a number: " putchars
stdin fgets 10 strtol.

jq

Works with: jq version 1.4

If the input consists of a JSON string followed by a JSON number, then the jq program consisting of . will read and echo the two values.

Works with: jq version 1.5

If the goal is to continue reading the input until a JSON string is found, and then continue reading the input until the integer value 75000 is encountered, then the following program could be used on the assumption that the inputs are all valid JSON.

def read(int):
  null | until( . == int;  "Expecting \(int)" | stderr | input);
  
def read_string:
  null | until( type == "string";  "Please enter a string" | stderr | input);

(read_string | "I see the string: \(.)"),
(read(75000) | "I see the expected integer: \(.)")
Output:

The following is a transcript showing the prompts (on stderr), responses (on stdin) and output (on stdout):

$ jq -n -r -f User_input.jq
"Please enter a string"
1
"Please enter a string"
"ok"
I see the string: ok
"Expecting 75000"
1
"Expecting 75000"
"ok"
"Expecting 75000"
75000
I see the expected integer: 75000

Julia

Works with: Julia version 0.6
print("String? ")
y = readline()
println("Your input was \"", y, "\".\n")
print("Integer? ")
y = readline()
try
    y = parse(Int, y)
    println("Your input was \"", y, "\".\n")
catch
    println("Sorry, but \"", y, "\" does not compute as an integer.")
end
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

System.file.stdout|write("Enter a String ");
string = System.file.stdin|readline();

Kotlin

// version 1.1

fun main(args: Array<String>) {
    print("Enter a string : ")
    val s = readLine()!!
    println(s)
    do {
        print("Enter 75000 : ")
        val number = readLine()!!.toInt()
    } while (number != 75000)
}

Lambdatalk

{input
 {@ type="text" 
    placeholder="Please enter a string and dblclick" 
    ondblclick="alert( 'You wrote « ' +
                       this.value +
                       ' » and it is ' +
                       ((isNaN(this.value)) ? 'not' : '') +
                       ' a number.' )"
}}

Please enter a string and dblclick

Input: Hello World
Output: You wrote « Hello World » and it is not a number.

Input: 123
Output: You wrote « 123 » and it is a number.

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
#string = read_input('Enter the string: ')

// get number
#number = integer(read_input('Enter the number: '))

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

Output:

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

LDPL

data:
myText is text
myNumber is number

procedure:
display "Enter some text: "
accept myText
display "Enter a number: "
accept myNumber

Liberty BASIC

Input "Enter a string. ";string$
Input "Enter the value 75000.";num

LIL

# User input/text, in LIL
write "Enter a string: "
set text [readline]

set num 0
while {[canread] && $num != 75000} {
    write "Enter the number 75000: "
    set num [readline]
}

print $text
print $num

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

Logtalk

Using an atom representation for strings and type-check failure-driven loops:

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

Output:

| ?- user_input::test.
Enter an integer: 75000.
Enter an atom: 'Hello world!'.
yes

LOLCODE

HAI 1.4
I HAS A string
GIMMEH string
I HAS A number
GIMMEH number
BTW converts number input to an integer
MAEK number A NUMBR
KTHXBYE

Lua

print('Enter a string: ')
s = io.stdin:read()
print('Enter a number: ')
i = tonumber(io.stdin:read())

M2000 Interpreter

Module CheckIt {
      Keyboard "75000"+chr$(13)
      Input "Integer:", A%
      \\ Input erase keyboard buffer, we can't place in first Keyboard keys for second input
      Keyboard  "Hello World"+Chr$(13)
      Input "String:", A$
      Print A%, A$
}
CheckIt

MACRO-10

        TITLE User Input

COMMENT !
     User Input ** PDP-10 assembly language (kjx, 2022)
      Assembler: MACRO-10   Operating system: TOPS-20

  This program reads a string (maximum of 80 characters) and
  a decimal number. The number is checked to be 75000. Invalid
  input (like entering characters instead of a decimal number)
  is detected, and an error message is printed in that case.
!

        SEARCH MONSYM,MACSYM
        .REQUIRE SYS:MACREL

        STDAC.                          ;Set standard register names.

STRING: BLOCK 20                        ;20 octal words = 80 characters.
NUMBER: BLOCK 1                         ;1 word for number.

        ;;
        ;; Execution starts here:
        ;;

GO::    RESET%                          ;Initialize process.

        ;; Print prompt:

        HRROI T1,[ASCIZ /Please type a string, 80 chars max.: /]
        PSOUT%
        
        ;; Read string from terminal:

        HRROI T1,STRING                 ;Pointer to string-buffer.
        MOVEI T2,^D80                   ;80 characters max.
        SETZ  T3                        ;No special ctrl-r prompt.
        RDTTY%                          ;Read from terminal.
          ERJMP ERROR                   ;  On error, go to ERROR.

        ;; Print second prompt:

NUMI:   HRROI T1,[ASCIZ /Please type the decimal number 75000: /]
        PSOUT%
        
        ;; Input number from terminal:
        
        MOVEI T1,.PRIIN                 ;Read from terminal.
        MOVEI T3,^D10                   ;Decimal input.
        NIN%                            ;Input number.
          ERJMP ERROR                   ;  On error, go to ERROR.
           
        ;; Make sure number is actually 75000.
        
        CAIE  T2,^D75000                ;Compare number...
          JRST [ HRROI T1,[ASCIZ /Number is not 75000! /]
                 PSOUT%                 ;  ...complain and
                 JRST  NUMI ]           ;  try again.
        MOVEM T2,NUMBER                 ;Store number if correct.

        ;; Now print out string and number:

        HRROI T1,STRING                 ;String ptr into T1.
        PSOUT%                          ;Print string.

        MOVEI T1,.PRIOU                 ;Print on standard output.
        MOVE  T2,NUMBER                 ;Load number into T2.
        MOVEI T3,^D10                   ;Decimal output.
        NOUT%                           ;And print the number.
          ERJMP ERROR                   ;  On error, go to ERROR.

        ;; End program:

        HALTF%                          ;Halt program.
        JRST  GO                        ;Allow for 'continue'-command.

        ;;
        ;; The following routine prints out an error message,
        ;; similar to perror() in C:
        ;;

ERROR:  MOVEI T1,.PRIOU                 ;Standard output.
        MOVE  T2,[.FHSLF,,-1]           ;Own program, last error.
        SETZ  T3,                       ;No size-limit on message.
        ERSTR%                          ;Print error-message.
          JFCL                          ;  Ignore errors from ERSTR.
          JFCL                          ;  dito.
        HALTF%                          ;Halt program.
        JRST  GO                        ;Allow for 'continue'-command.

        END GO

Example output:

@ exec uinput
MACRO:  User
LINK:   Loading
[LNKXCT USER execution]
Please type a string, 80 chars max.: This is a test.
Please type the decimal number 75000: 74998
Number is not 75000! Please type the decimal number 75000: 74999
Number is not 75000! Please type the decimal number 75000: 75000
This is a test.
75000
@ _

Maple

printf("String:"); string_value := readline();
printf("Integer: "); int_value := parse(readline());

Mathematica / Wolfram Language

mystring = InputString["give me a string please"];
myinteger = Input["give me an integer please"];

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

Maxima

/* String routine */
block(
s:read("enter a string"),
if stringp(s) then print(s,"is an actual string") else "that is not a string")$

/* Number routine */
block(
n:read("enter a number"),
if numberp(n) then print(n,"is an actual number") else "that is not a number")$

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

min

Works with: min version 0.19.3
"Enter a string" ask
"Enter an integer" ask int

Mirah

s = System.console.readLine()

puts s

mIRC Scripting Language

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

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.

MUMPS

TXTINP
 NEW S,N
 WRITE "Enter a string: "
 READ S,!
 WRITE "Enter the number 75000: "
 READ N,!
 KILL S,N
 QUIT

Nanoquery

string  = str(input("Enter a string: "))
integer = int(input("Enter an integer: "))

Neko

/**
 User input/Text, in Neko
 Tectonics:
   nekoc userinput.neko
   neko userinput
*/

var stdin = $loader.loadprim("std@file_stdin", 0)()
var file_read_char = $loader.loadprim("std@file_read_char", 1)

/* Read a line from file f into string s returning length without any newline */
var NEWLINE = 10
var readline = function(f, s) {
    var len = 0
    var ch
    while true {
        try ch = file_read_char(f) catch a break;
        if ch == NEWLINE break;
        if $sset(s, len, ch) == null break; else len += 1
    }
    return $ssub(s, 0, len)
}

$print("Enter a line of text, then the number 75000\n")

try {
    var RECL = 132
    var str = $smake(RECL)
    var userstring = readline(stdin, str)
    $print(":", userstring, ":\n")

    var num = $int(readline(stdin, str))
    if num == 75000 $print("Rosetta Code 75000, for the win!\n")
    else $print("Sorry, need 75000\n")
} catch problem $print("Exception: ", problem, "\n")
Output:
prompt$ nekoc userinput.neko
prompt$ neko userinput.n
Enter a line of text, then the number 75000
this is a line of text
:this is a line of text:
75000
Rosetta Code 75000, for the win!

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

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

newLISP

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

Nim

import rdstdin, strutils

let str = readLineFromStdin "Input a string: "
let num = parseInt(readLineFromStdin "Input an integer: ")

NS-HUBASIC

10 INPUT "ENTER A STRING: ",STRING$
20 PRINT "YOU ENTERED ";STRING$;"."
30 INPUT "ENTER AN INTEGER: ",INTEGER
40 PRINT "YOU ENTERED";INTEGER;"."

Nu

{
	String: (input "Enter a string: ")
	Number: (input "Enter an integer: ")
}
Output:
Enter a string: Hello world!
Enter an integer: 75000
╭────────┬──────────────╮
│ String │ Hello world! │
│ Number │ 75000        │
╰────────┴──────────────╯

Oberon-2

Works with: oo2c
MODULE InputText;
IMPORT 
  In,
  Out;
VAR
  i: INTEGER;
  str: ARRAY 512 OF CHAR;
BEGIN
  Out.String("Enter a integer: ");Out.Flush();In.Int(i);
  Out.String("Enter a string: ");Out.Flush();In.String(str);
END InputText.

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();
    }
  }
}

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

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

Oforth

import: console

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

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

PARI/GP

s=input();
n=eval(input());

Pascal

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

Perl

print "Enter a string: "; 
my $string = <>;
print "Enter an integer: ";
my $integer = <>;

Phix

?prompt_string("Enter any string:")
?prompt_number("Enter the number 75000:",{75000,75000})
Output:
Enter any string:abc
"abc"
Enter the number 75000:123
A number from 75000 to 75000 is expected here - try again
Enter the number 75000:75000
75000

Phixmonti

/# Rosetta Code problem: https://rosettacode.org/wiki/User_input/Text
by Galileo, 10/2022 #/

"Enter any string: " input nl
true while
    75000 "Enter the number " over tostr chain ": " chain input
    nl tonum over == not
endwhile
drop pstack
Output:
Enter any string: Hello
Enter the number 75000: 1000
Enter the number 75000: 75000

["Hello", 75000]

=== Press any key to exit ===

PHP

Works with: CLI SAPI
#!/usr/bin/php
<?php
$string = fgets(STDIN);
$integer = (int) fgets(STDIN);

Picat

main =>
  print("Enter a string: "),
  String = read_line(),
  print("Enter a number: "),
  Number = read_int(),
  println([string=String,number=Number]).

PicoLisp

(in NIL  # Guarantee reading from standard input
   (let (Str (read)  Num (read))
      (prinl "The string is: \"" Str "\"")
      (prinl "The number is: " Num) ) )

Pike

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

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');

Plain English

To run:
Start up.
Demonstrate input.
Wait for the escape key.
Shut down.
 
To demonstrate input:
Write "Enter a string: " to the console without advancing.
Read a string from the console.
Write "Enter a number: " to the console without advancing.
Read a number from the console.
\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:

Output:
Enter a string: abc
Enter a number: 123
The string: abc
The number: 123

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();

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.

PowerShell

$string = Read-Host "Input a string"
[int]$number = Read-Host "Input a number"

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

Python

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: ")

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.

Quackery

The word $->n 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.

$ "Please enter a string: " input
say 'You entered: "' echo$ say '"' cr cr
 
$ "Please enter an integer: " input
trim reverse trim reverse
$->n iff 
  [ say "You entered: " echo cr ]
else
  [ say "That was not an integer." cr 
    drop ]
Output:
Please enter a string: 3-ply sisal twine
You entered: "3-ply sisal twine"

Please enter an integer: 75000
You entered: 75000

R

Works with: R version 2.81
stringval <- readline("String: ")
intval <- as.integer(readline("Integer: "))

Racket

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

Raku

(formerly Perl 6)

my $str = prompt("Enter a string: ");
my $int = prompt("Enter a integer: ");

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:

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\>";});
}

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

'Input a string: '   print expect as str
'Input an integer: ' print expect 0 prefer as num

REBOL

REBOL [
	Title: "Textual User Input"
	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...'.

Red

n: ask "Please enter # 75000: " str: ask "Please enter any string: "

Retro

:example ("-)
  '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 ;

REXX

Note:   all of the following would be accepted as being numerically equal to   75000:

  •   7.5E+0004
  •   75000.
  •   750000e-01
  •   000075000.0000
  •       75000           (with leading and/or trailing blanks)
  •   and others

If the intent was to have the user enter the string exactly as   75000,
then the REXX   do   statement should be replaced with:

 do  until userNumber==75000
/*REXX program prompts & reads/obtains a string, and also the number 75000 from terminal*/
say 'Please enter a string:'                     /*issue a prompt message to the term.  */
parse pull userString                            /*the (char) string can be any length. */
                                                 /* [↑]  the string could be null/empty.*/
  do  until userNumber=75000                     /*repeat this loop until satisfied.    */
  say                                            /*display a blank line to the terminal.*/
  say 'Please enter the number 75000'            /*display a nice prompt message to term*/
  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. */

Ring

see "Enter a string : " give s 
see "Enter an integer : " give i 
see "String  = " + s + nl
see "Integer = " + i + nl

Robotic

input string "Enter string:"
set "$str" to "input"
input string "Enter number:"
set "number" to "input"
[ "You entered:"
[ "&$str&"
[ "&number&"
end

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"
: "incorrect"
input string "Enter number:"
set "number" to "input"
if "number" != "(75000)" then "incorrect"
[ "You entered:"
[ "&$str&"
[ "&number&"
end

RPL

"Enter text" { "" 𝛼 } INPUT    @ Set keyboard alpha mode
   75000 → string n75000
   ≪ DO
        "Enter number " n + "" INPUT
     UNTIL n →STR == END
     string number
≫  ≫ 'TASK' STO 

Ruby

Works with: Ruby version 1.8.4
print "Enter a string: "
s = gets
printf "Enter an integer: "
i = gets.to_i   # If string entered, will return zero
printf "Enter a real number: "
f = Float(gets) rescue nil   # converts a floating point number or returns nil
puts "String  = #{s}"
puts "Integer = #{i}"
puts "Float   = #{f}"

Rust

This program shows all the proper error handling.

use std::io::{self, Write};
use std::fmt::Display;
use std::process;

fn main() {
    let s = grab_input("Give me a string")
        .unwrap_or_else(|e| exit_err(&e, e.raw_os_error().unwrap_or(-1)));

    println!("You entered: {}", s.trim());

    let n: i32 = grab_input("Give me an integer")
        .unwrap_or_else(|e| exit_err(&e, e.raw_os_error().unwrap_or(-1)))
        .trim()
        .parse()
        .unwrap_or_else(|e| exit_err(&e, 2));

    println!("You entered: {}", n);
}

fn grab_input(msg: &str) -> io::Result<String> {
    let mut buf = String::new();
    print!("{}: ", msg);
    try!(io::stdout().flush());

    try!(io::stdin().read_line(&mut buf));
    Ok(buf)
}

fn exit_err<T: Display>(msg: T, code: i32) -> ! {
    let _ = writeln!(&mut io::stderr(), "Error: {}", msg);
    process::exit(code)
}

Scala

print("Enter a number: ")
val i=Console.readLong  // Task says to enter 75000
print("Enter a string: ")
val s=Console.readLine

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)

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;

Sidef

Using the read(Type) built-in function:

var s = read(String);
var i = read(Number);    # auto-conversion to a number

or using the Sys.readln(msg) method:

var s = Sys.readln("Enter a string: ");
var i = Sys.readln("Enter a number: ").to_i;

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.

Smalltalk

'Enter a number: ' display.
a := stdin nextLine asInteger.

'Enter a string: ' display.
b := stdin nextLine.

smart BASIC

NOTE: The INPUT command uses a colon (:) as opposed to a comma (,) or semi-conlon (;) like other forms of BASIC.

INPUT "Enter a string.":a$
INPUT "Enter the value 75000.":n

SNOBOL4

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

SPL

In SPL all console input is text, so number should be converted from text using #.val function.

text = #.input("Input a string")
number = #.val(#.input("Input a number"))

SparForte

As a structured script.

#!/usr/local/bin/spar
  
pragma annotate( summary, "get_string" )
       @( description, "Input a string and the integer 75000 from the text console." )
       @( see_also, "https://rosettacode.org/wiki/User_input/Text" )
       @( author, "Ken O. Burtch" );
pragma license( unrestricted );

pragma restriction( no_external_commands );

procedure get_string is
  s : unbounded_string;
  i : integer;
begin
  s := get_line;
  i := integer( numerics.value( get_line ) );
  ? s @ i;
exception when others =>
  put_line( standard_error, "the value is not valid" );
end get_string;

As a unstructured script and no exception handling.

s := get_line;
i := numerics.value( get_line );
? s @ i;

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

Swift

Works with: Swift version 2.x+
print("Enter a string: ", terminator: "")
if let str = readLine() {
  print(str)
}
Works with: Swift version 5.x+
print("Enter a string: ", terminator: "")
guard let str = readLine() else {
    fatalError("Nothing read!")
}
print(str)
print("Enter a number: ", terminator: "")
guard let nstr = readLine(), let num = Int(nstr) else {
    fatalError("Not a number!")
}
print(num)

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"

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

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

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

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

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
#!/bin/sh

read string
read integer
read -p 'Enter a number: ' number
echo "The number is $number"

Ursa

#
# user input
#

# in ursa, the type of data expected must be specified
decl string str
decl int i

out "input a string: " console
set str (in string console)
out "input an int:   " console
set i (in int console)

out "you entered " str " and " i endl console

VBA

Public Sub text()
    Debug.Print InputBox("Input a string")
    Debug.Print InputBox("Input the integer 75000", "Input an integer", 75000, Context = "Long")
End Sub

Vedit macro language

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

Visual Basic .NET

Platform: .NET

Works with: Visual Basic .NET version 9.0+

Input an Integer

Dim i As Integer
Console.WriteLine("Enter an Integer")
i = Console.ReadLine()

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

Input a String

Dim i As String
Console.WriteLine("Enter a String")
i = Console.ReadLine()

V (Vlang)

import os

fn main() {
    s := os.input('Enter string').int()
    if s == 75000 {
        println('good')
    } else {
        println('bad')
    }
}

Input conversion with Error Handling

import os
import strconv

fn main() {
    s := strconv.atoi(os.input('Enter string')) ?
    if s == 75000 {
        println('good')
    } else {
        println('bad $s')
    }
}

Wee Basic

print 1 "Enter a string."
input string$
print 1 "Enter an integer."
input integer

Wren

import "io" for Stdin, Stdout

var string
while (true) {
    System.write("Enter a string : ")
    Stdout.flush()
    string = Stdin.readLine()
    if (string.count == 0) {
        System.print("String cannot be empty, try again.")
    } else {
        break
    }
}

var number
while (true) {
    System.write("Enter a number : ")
    Stdout.flush()
    number = Num.fromString(Stdin.readLine())
    if (!number || !number.isInteger) {
        System.print("Please enter a vaid integer, try again.")
    } else {
        break
    }
}

System.print("\nYou entered:")
System.print("  string: %(string)")
System.print("  number: %(number)")
Output:
Enter a string : Rosetta Code
Enter a number : 75000

You entered:
  string: Rosetta Code
  number: 75000

XLISP

READ-LINE reads a line of input as a string; READ reads an expression, of arbitrary complexity.

(display "Enter a string: ")
(define s (read-line))
(display "Yes, ")
(write s)
(display " is a string.") ;; no need to verify, because READ-LINE has to return a string
(newline)
(display "Now enter the integer 75000: ")
(define n (read))
(display
    (cond
        ((not (integerp n))
            "That's not even an integer." )
        ((/= n 75000)
            "That is not the integer 75000." )
        (t
            "Yes, that is the integer 75000." ) ) )
Output:
Enter a string: Rosetta Code
Yes, "Rosetta Code" is a string.
Now enter the integer 75000: 75000
Yes, that is the integer 75000.

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.

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
]

Example output:

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

zkl

str:=ask("Gimmie a string: ");
n:=ask("Type 75000: ").toInt();

ZX Spectrum Basic

10 INPUT "Enter a string:"; s$
20 INPUT "Enter a number: "; n