
Input a string and the integer 75000 from the text console.
See also:User input/Graphical
Currently, there is a limit on how many <syntaxhighlight> tags can appear on a page, so only the first few languages get highlighting, the rest are shown in monochrome.
You could try "manual highlighting", possibly using one of the highlighters onSyntax highlighting using Mediawiki formatting or something similar.
V string = input(‘Input a string: ’)V number = Float(input(‘Input a number: ’))
P:Iisns
//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 .dataenterText:.asciz "Enter text: "carriageReturn: .asciz "\n"//Read Buffer.bss buffer: .skip BUFFERSIZE.text.global _start quadEnterText: .quad enterTextquadBuffer: .quad bufferquadCarriageReturn:.quad carriageReturnwriteMessage: mov x2,0 // reset size counter to 0checkSize: // 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 // loopoutput: 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
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)RETURNScreenshot from Atari 8-bit computer
Please enter a text: Atari 130XEPlease enter number 75000: 123Please enter number 75000: 76000Please enter number 75000: 75000Text: Atari 130XENumber: 75000
functionGet_StringreturnStringisLine:String(1..1_000);Last:Natural;beginGet_Line(Line,Last);returnLine(1..Last);endGet_String;functionGet_IntegerreturnIntegerisS:constantString:=Get_String;beginreturnInteger'Value(S);-- may raise exception Constraint_Error if value entered is not a well-formed integerendGet_Integer;
The functions above may be called as shown below
My_String:String:=Get_String;My_Integer:Integer:=Get_Integer;
Another:
withAda.Text_IO,Ada.Integer_Text_IO;procedureUser_InputisI:Integer;beginAda.Text_IO.Put("Enter a string: ");declareS:String:=Ada.Text_IO.Get_Line;beginAda.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));endUser_Input;
Unbounded IO:
withAda.Text_IO,Ada.Integer_Text_IO,Ada.Strings.Unbounded,Ada.Text_IO.Unbounded_IO;procedureUser_Input2isS:Ada.Strings.Unbounded.Unbounded_String;I:Integer;beginAda.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));endUser_Input2;
print("Enter a string: ");STRING s := read string;print("Enter a number: ");INT i := read int;~begin string(80) s; integer n; write( "Enter a string > " ); read( s ); write( "Enter an integer> " ); read( n )end.
Version: hopper-FLOW!
#include <flow.h>#import lib/input.bas.lib#include include/flow-input.hDEF-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
Input an string : Juanita Pérez Input an integer: 75000.789 Juanita Pérez 75000
str←⍞int←⎕
(let str (input "str> "))(let num (toNumber (input "num> ")))(if (nil? num) (print "num is not a valid number"))
/* 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 */.dataszMessDeb: .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 calliAdrszMessDeb: .int szMessDebiAdrszMessNum: .int szMessNumiAdrsBuffer: .int sBufferiAdrszCarriageReturn: .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 100f99: /* overflow error */ ldr r0,=szMessErrDep bl affichageMess mov r0,#0 @ return zero if error100: pop {r1-r7} @ restaur other registers pop {fp,lr} @ restaur 2 registers bx lr @return procedure /* constante program */iMaxi: .int 1073741824szMessErrDep: .asciz "Too large: overflow 32 bits.\n"str:input"Enter a string:"num:to:integerinput"Enter an integer:"print["Got:"str","num]
Enter a string: hello worldEnter an integer: 1986Got: hello world , 1986
DllCall("AllocConsole")FileAppend,pleasetypesomething`n,CONOUT$FileReadLine,line,CONIN$,1msgbox%lineFileAppend,pleasetype '75000'`n,CONOUT$FileReadLine,line,CONIN$,1msgbox%line
this one takes input regardless of which application has focus.
TrayTip,Input:,Typeastring:Input(String)TrayTip,Input:,Typeanint:Input(Int)TrayTip,Done!,Inputwasrecieved.Msgbox,Youentered"%String%"and"%Int%"ExitAppReturnInput(ByRefOutput){Loop{Input,Char,L1,{Enter}{Space}IfErrorLevelcontainsEnterBreakElseIfErrorLevelcontainsSpaceOutput.=" "ElseOutput.=CharTrayTip,Input:,%Output%}}
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}'enterastring:helloworldok,helloworld/075000ok,75000/75000
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. Seethis table of tokens and their codes for reference.
Disp "String:"input→Alength(A)→L.Copy the string to a safe locationCopy(A,L₁,L).Display the stringDisp "You entered:",iFor(I,0,L-1) Disp {L₁+I}►CharEndDisp iDisp "Integer:",iinput→Blength(B)→L.Parse the string and convert to an integer0→CFor(I,0,L-1) {B+I}-'0'→N If N>10 .Error checking Disp "Not a number",i Return End C*10+N→CEnd.Display and check the integerDisp "You entered:",i,C►Dec,iIf C≠7500Disp "That isn't 7500"End* NB: whitespace insignificance and case insensitivity * are used in the field name.IDENTIFICATIONDIVISION.PROGRAM-ID.USERINPUT.DATADIVISION.01HUNDREDCHARSTRINGPICTURE ISX(100).01FIVEDIGITNUMBERPICTURE IS9(5).PROCEDUREDIVISION.DISPLAY"Enter a string of appropriate length: "WITHNOADVANCINGACCEPTHundredCharString.DISPLAY"Enter a number (preferably 75000): "WITHNOADVANCINGACCEPTFiveDigitNumber.
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 Basicnever appends a question mark.
INPUT"Enter a string";s$INPUT"Enter a number: ",i%
Output (QBasic):
Enter a string? fooEnter a number: 1
10INPUT"ENTER A STRING: ";S$20INPUT"ENTER A NUMBER: ";I:I=INT(I)
When using the prompt feature of theINPUT 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 theINPUT command. Any other behavior would have to come from a user-built routine using theGET 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.
10input"what is a word i should remember";a$20print"thank you."30input"will you please type the number 75000";nn40ifnn<>75000thenprint"i'm sorry, that's not right.":goto3050print"thank you.":print"you provided the following values:"60printa$70printnn80end
Output
READY.RUNWHAT IS A WORD I SHOULD REMEMBER? PANCAKETHANK YOU.WILL YOU PLEASE TYPE THE NUMBER 75000? NO.?REDO FROM STARTWILL YOU PLEASE TYPE THE NUMBER 75000? 848I'M SORRY, THAT'S NOT RIGHT.WILL YOU PLEASE TYPE THE NUMBER 75000? 75000THANK YOU.YOU PROVIDED THE FOLLOWING VALUES:PANCAKE 75000READY.█
10INPUTA$20INPUTB30IFB<>75000THEN2040PRINTA$,B
100 INPUT PROMPT "Enter a number: ":NUM110 INPUT PROMPT "Enter a string: ":ST$
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&
inputstring"Please enter a string: ",sdoinput"Please enter 75000 : ",iuntili=75000printprints,i
input "Please enter a string: "; s$while i <> 75000 input "Please enter 75000 : "; iwendprintprint s$; chr$(9); i
PRINT"Please enter a string";INPUTs$DOPRINT"Please enter 75000 ";INPUTiLOOPUntili=75000PRINTPRINTs$,iEND
input"Please enter a string: "s$repeatinput"Please enter 75000 : "iuntili=75000printprints$,chr$(9),i
10PRINT"ENTER A STRING"20INPUTS$30PRINT"YOU ENTERED: ";S$40PRINT"NOW ENTER THE NUMBER 75000"50INPUTN60IFN=75000THENSTOP70PRINT"NO, ";80GOTO40
@echo offsetlocal enableextensionsset/pistr=set/pinum=set/aval=inumifnot"%val%"=="75000"echo Second input should be 75000.
INPUTLINE"Enter a string: "string$INPUT"Enter a number: "numberPRINT"String = """string$""""PRINT"Number = ";number
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: "^,_&@
( 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));
{?} !doitEnter a stringabacusEnter a number75000hI said:"a number"!Enter a number75000mystring is abacusmynumber is 75000#include<stdio.h>#include<stdlib.h>intmain(void){// Get a string from stdincharstr[BUFSIZ];puts("Enter a string: ");fgets(str,sizeof(str),stdin);// Get 75000 from stdinlongnum;charbuf[BUFSIZ];do{puts("Enter 75000: ");fgets(buf,sizeof(buf),stdin);num=strtol(buf,NULL,10);}while(num!=75000);returnEXIT_SUCCESS;}
#include<gadget/gadget.h>LIB_GADGET_STARTMainCls;Stringtext;intnumber=0;At5,5;Print"Enter text : ";Atrow7;Print"Enter ‘75000’: ";Atcol20;Atrow5;Fn_let(text,Input(text,30));Freesecuretext;Atrow7;Stack{while(number!=75000)/*into stack, Input() not need var*/number=Str2int(Input(NULL,6));}Stack_off;Prnl;End
$ ./tests/input_cons Enter text : Juanita la mañosa Enter ‘75000’: 75000 $
usingSystem;namespaceC_Sharp_Console{classexample{staticvoidMain(){stringword;intnum;Console.Write("Enter an integer: ");num=Console.Read();Console.Write("Enter a String: ");word=Console.ReadLine();}}}
#include<iostream>#include<string>usingnamespacestd;intmain(){// while probably all current implementations have int wide enough for 75000, the C++ standard// only guarantees this for long int.longintinteger_input;stringstring_input;cout<<"Enter an integer: ";cin>>integer_input;cout<<"Enter a string: ";cin>>string_input;return0;}
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 thefail 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 (withif (!cin) // handle error) after the first input, and then clear the error (withcin.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.
sharedvoidrun(){print("enter any text here");valuetext=process.readLine();print(text);print("enter the number 75000 here");if(isIntegernumber=Integer.parse(process.readLine()else"")){print("``number == 75k then number else "closeenough"``");}else{print("That was not a number per se.");}}
(import'(java.utilScanner))(defscan(Scanner.*in*))(defs(.nextLinescan))(defn(.nextIntscan))
IDENTIFICATIONDIVISION.PROGRAM-ID.Get-Input.DATADIVISION.WORKING-STORAGESECTION.01Input-StringPIC X(30).01Input-IntPIC 9(5).PROCEDUREDIVISION.DISPLAY"Enter a string:"ACCEPTInput-StringDISPLAY"Enter a number:"ACCEPTInput-IntGOBACK.
(formatt"Enter some text: ")(let((s(read-line)))(formatt"You entered ~s~%"s))(formatt"Enter a number: ")(let((n(read)))(if(numberpn)(formatt"You entered ~d.~%"n)(formatt"That was not a number.")))
puts"You entered:#{gets}"beginputs"You entered:#{gets.not_nil!.chomp.to_i}"rescueexputsexend
Example with valid input:
HelloYou entered: Hello75000You entered: 75000
Example with invalid input:
HelloYou entered: HelloGoodbyeInvalid Int32: Goodbye
importstd.stdio;voidmain(){longnumber;write("Enter an integer: ");readf("%d",&number);char[]str;write("Enter a string: ");readf(" %s\n",&str);writeln("Read in '",number,"' and '",str,"'");}
import'dart:io'showstdout,stdin;main(){stdout.write('Enter a string: ');finalstring_input=stdin.readLineSync();intnumber_input;do{stdout.write('Enter the number 75000: ');varnumber_input_string=stdin.readLineSync();try{number_input=int.parse(number_input_string);if(number_input!=75000)stdout.writeln('$number_input is not 75000!');}onFormatException{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');}
programUserInputText;{$APPTYPE CONSOLE}usesSysUtils;vars:string;lStringValue:string;lIntegerValue:Integer;beginWriteLn('Enter a string:');Readln(lStringValue);repeatWriteLn('Enter the number 75000');Readln(s);lIntegerValue:=StrToIntDef(s,0);iflIntegerValue<>75000thenWriteln('Invalid entry: '+s);untillIntegerValue=75000;end.
input s: !print\ s !decode!utf-8 !read-line!stdinlocal :astring input "Enter a string: "truewhile: try: to-num input "Enter the number 75000: " /= 75000 catch value-error: true
write "Enter a string: "a$ = inputprint ""repeat write "Enter the number 75000: " h = number input print "" until h = 75000.print a$ & " " & h
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()}a=IO.gets("Enter a string: ")|>String.stripb=IO.gets("Enter an integer: ")|>String.strip|>String.to_integerf=IO.gets("Enter a real number: ")|>String.strip|>String.to_floatIO.puts"String =#{a}"IO.puts"Integer =#{b}"IO.puts"Float =#{f}"
text string ← ask(text, "Enter a string: ")int numberfor ever number ← ask(int, "Enter the integer 75000: ") if number æ 75000 do break endendwriteLine()writeLine(string)writeLine(number)
Enter a string: HelloEnter the integer 75000: 75000.12Enter the integer 75000: 32Enter the integer 75000: 75000Hello75000
{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: ").
include get.esequence satom ns = prompt_string("Enter a string:")puts(1, s & '\n')n = prompt_number("Enter a number:",{})printf(1, "%d", n)openSystemletask_for_inputs=printf"%s (End with Return): "sConsole.ReadLine()[<EntryPoint>]letmainargv=ask_for_input"Input a string"|>ignoreask_for_input"Enter the number 75000"|>ignore0
"Enter a string: "writereadln"Enter a number: "writereadlnstring>number
printl("Enter a string:")str = input()printl("Enter a number:")n = int(input())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;!.
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")) }}:INPUT$( n -- addr n )PADSWAPACCEPTPADSWAP;
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.16INPUT$DUP>R>NUMBERNIPNIPR><>DUP0=IFNIPTHEN;
:INPUT#( -- n true | d 1 | false )16INPUT$SNUMBER?;
:INPUT#( -- n true | false )16INPUT$NUMBER?NIPDUP0=IFNIPTHEN;
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.
:input#beginrefilldropblparse-word( a n)numbererror?( n f)while( n)drop( --)repeat( n);
Here is an example that puts it all together:
:TEST."Enter your name:"80INPUT$CR."Hello there,"TYPECR."Enter a number:"INPUT#CRIF."Your number is".ELSE."That's not a number!"THENCR;
character(20)::sinteger::iprint*,"Enter a string (max 20 characters)"read*,sprint*,"Enter the integer 75000"read*,i
' FB 1.05.0 Win64DimsAsStringDimiASIntegerInput"Please enter a string : ";sDoInput"Please enter 75000 : ";iLoopUntili=75000PrintPrints,iSleep
Sample input/output
Please enter a string : ? RosettaPlease enter 75000 : ? 70000Please enter 75000 : ? 75000Rosetta 75000
s = input["Enter a string: "]i = parseInt[input["Enter an integer: "]]
void local fn DoIt window 1, @"User/input Text" CFStringRef string = input @"Enter a string:" print string CFStringRef number = @"" while ( intval(number) != 75000 ) number = input @"Enter the integer 75000", @"0123456789", YES, 5 wend print numberend fnfn DoItHandleEvents
Run withgodot --headless --script <file>
extendsMainLoopfunc_process(_delta:float)->bool:printraw("Input a string: ")varread_line:=OS.read_string_from_stdin()# Mote that this retains the newline.printraw("Input an integer: ")varread_integer:=int(OS.read_string_from_stdin())print("read_line =%s"%read_line.trim_suffix("\n"))print("read_integer =%d"%read_integer)returntrue# Exit instead of looping
Go has C-like Scan and Scanf functions for quick and dirty input:
packagemainimport"fmt"funcmain(){varsstringvariintif_,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.
packagemainimport("bufio""fmt""os""strconv""strings")funcmain(){in:=bufio.NewReader(os.Stdin)fmt.Print("Enter string: ")s,err:=in.ReadString('\n')iferr!=nil{fmt.Println(err)return}s=strings.TrimSpace(s)fmt.Print("Enter 75000: ")s,err=in.ReadString('\n')iferr!=nil{fmt.Println(err)return}n,err:=strconv.Atoi(strings.TrimSpace(s))iferr!=nil{fmt.Println(err)return}ifn!=75000{fmt.Println("fail: not 75000")return}fmt.Println("Good")}
Doesn't check if number is valid.
"#{STDIN.gets}""#{STDIN.gets}"~7500075000:7500075000
word=System.in.readLine()num=System.in.readLine().toInteger()
importSystem.IO(hFlush,stdout)main=doputStr"Enter a string: "hFlushstdoutstr<-getLineputStr"Enter an integer: "hFlushstdoutnum<-readLn::IOIntputStrLn$str++(shownum)
Note::: IO Int is only there to disambiguate what type we wanted fromread. Ifnum 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.
print "Enter a string: "let s scan strprint "Enter a number: "let n scan int
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));The following works in both Icon and Unicon:
proceduremain()writes("Enter something: ")s:=read()write("You entered: "||s)writes("Enter 75000: ")if(i:=integer(read()))thenwrite(if(i=75000)then"correct"else"incorrect")elsewrite("you must enter a number")end
string:=FileclonestandardInputreadLine("Enter a string: ")integer:=FileclonestandardInputreadLine("Enter 75000: ")asNumber
Solution
require'misc'NB. load system scriptprompt'Enter string: '0".prompt'Enter an integer: '
Note thatrequire'misc' is old - efforts to optimize by loading misc utilities in a fine grained fashion mean that currently (J 805) that should berequire'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 sessionEnterstring:HelloWorldHelloWorld0".prompt'Enter an integer: 'NB. output integer to sessionEnteraninteger:7500075000mystring=:prompt'Enter string: 'NB. store string as nounEnterstring:HelloRosettaCodemyinteger=:0".prompt'Enter an integer: 'NB. store integer as nounEnteraninteger:75000mystring;myintegerNB. show contents of nouns┌──────────────────┬─────┐│HelloRosettaCode│75000│└──────────────────┴─────┘
importjava.util.Scanner;publicclassGetInput{publicstaticvoidmain(String[]args)throwsException{Scanners=newScanner(System.in);System.out.print("Enter a string: ");Stringstr=s.nextLine();System.out.print("Enter an integer: ");inti=Integer.parseInt(s.next());}}
or
importjava.util.Scanner;publicclassGetInput{publicstaticvoidmain(String[]args){Scannerstdin=newScanner(System.in);Stringstring=stdin.nextLine();intnumber=stdin.nextInt();}}
and only withcscript.exe
WScript.Echo("Enter a string");varstr=WScript.StdIn.ReadLine();varval=0;while(val!=75000){WScript.Echo("Enter the integer 75000");val=parseInt(WScript.StdIn.ReadLine());}
print("Enter a string");varstr=readline();varval=0;while(val!=75000){print("Enter the integer 75000");val=parseInt(readline());}
constreadline=require("readline");constrl=readline.createInterface({input:process.stdin,output:process.stdout});rl.question("Enter a string: ",(str)=>{console.log(str);rl.close();});rl.question("Enter a number: ",(n)=>{console.log(parseInt(n));rl.close();});
"Enter a string: " putcharsstdin fgets"Enter a number: " putcharsstdin fgets 10 strtol.
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.
If the goal is to continue reading the input until a JSON string isfound, and then continue reading the input until the integer value 75000 isencountered, then the following program could be used on the assumption thatthe 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: \(.)")
The following is a transcript showing the prompts (on stderr), responses (on stdin) and output (on stdout):
$jq-n-r-fUser_input.jq"Please enter a string"1"Please enter a string""ok"Iseethestring:ok"Expecting 75000"1"Expecting 75000""ok""Expecting 75000"75000Iseetheexpectedinteger:75000
print("String? ")y=readline()println("Your input was\"",y,"\".\n")print("Integer? ")y=readline()tryy=parse(Int,y)println("Your input was\"",y,"\".\n")catchprintln("Sorry, but\"",y,"\" does not compute as an integer.")end
String? cheeseYour input was "cheese".Integer? 75000Your input was "75000".mike@harlan:~/rosetta/julia$ julia user_input_text.jlString? theoryYour input was "theory".Integer? 75,000Sorry, but "75,000" does not compute as an integer.
System.file.stdout|write("Enter a String ");string = System.file.stdin|readline();// version 1.1funmain(args:Array<String>){print("Enter a string : ")vals=readLine()!!println(s)do{print("Enter 75000 : ")valnumber=readLine()!!.toInt()}while(number!=75000)}
{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.' )"}}PleaseenterastringanddblclickInput:HelloWorldOutput:Youwrote«HelloWorld»anditisnotanumber.Input:123Output:Youwrote«123»anditisanumber.
#!/usr/bin/lasso9defineread_input(prompt::string)=>{local(string)// display promptstdout(#prompt)// the following bits wait until the terminal gives you back a line of inputwhile(not#stringor#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 resultstdoutnl(#string+' ('+#string->type+') | '+#number+' ('+#number->type+')')
Output:
Enter the string: HelloEnter the number: 1234Hello (string) | 1234 (integer)
data:myText is textmyNumber is numberprocedure:display "Enter some text: "accept myTextdisplay "Enter a number: "accept myNumber
Input "Enter a string. ";string$Input "Enter the value 75000.";num
# User input/text, in LILwrite"Enter a string: "settext[readline]setnum0while{[canread]&&$num!=75000}{write"Enter the number 75000: "setnum[readline]}print$textprint$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 75000show map "number? :input ; [false true]make "input readword ; in: 75000show :input + 123 ; 75123 make "input readword ; in: string 75000show :input ; string 75000
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
HAI 1.4I HAS A stringGIMMEH stringI HAS A numberGIMMEH numberBTW converts number input to an integerMAEK number A NUMBRKTHXBYE
print('Enter a string: ')s=io.stdin:read()print('Enter a number: ')i=io.stdin:read"n"
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$}CheckItTITLE User InputCOMMENT ! 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 uinputMACRO: UserLINK: Loading[LNKXCT USER execution]Please type a string, 80 chars max.: This is a test.Please type the decimal number 75000: 74998Number is not 75000! Please type the decimal number 75000: 74999Number is not 75000! Please type the decimal number 75000: 75000This is a test.75000@ _
printf("String:");string_value:=readline();printf("Integer: ");int_value:=parse(readline());
mystring=InputString["give me a string please"];myinteger=Input["give me an integer please"];
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: ')Inputstring:'Hello'ans=Hello>>input('Input number: ')Inputnumber:75000ans=75000>>input('Input number, the number will be stored as a string: ','s')Inputnumber,thenumberwillbestoredasastring:75000ans=75000
/* String routine */block(s:read("enter a string"),ifstringp(s)thenprint(s,"is an actual string")else"that is not a string")$/* Number routine */block(n:read("enter a number"),ifnumberp(n)thenprint(n,"is an actual number")else"that is not a number")$
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).
"Enter a string" ask"Enter an integer" ask int
s = System.console.readLine()puts s
alias askmesomething { echo -a You answered: $input(What's your name?, e)}MODULEInputEXPORTSMain;IMPORTIO,Fmt;VARstring:TEXT;number:INTEGER;BEGINIO.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");ENDInput.
TXTINP NEW S,N WRITE "Enter a string: " READ S,! WRITE "Enter the number 75000: " READ N,! KILL S,N QUIT
string = str(input("Enter a string: "))integer = int(input("Enter an integer: "))/** User input/Text, in Neko Tectonics: nekoc userinput.neko neko userinput*/varstdin=$loader.loadprim("std@file_stdin",0)()varfile_read_char=$loader.loadprim("std@file_read_char",1)/* Read a line from file f into string s returning length without any newline */varNEWLINE=10varreadline=function(f,s){varlen=0varchwhiletrue{trych=file_read_char(f)catchabreak;ifch==NEWLINEbreak;if$sset(s,len,ch)==nullbreak;elselen+=1}return$ssub(s,0,len)}$print("Enter a line of text, then the number 75000\n")try{varRECL=132varstr=$smake(RECL)varuserstring=readline(stdin,str)$print(":",userstring,":\n")varnum=$int(readline(stdin,str))ifnum==75000$print("Rosetta Code 75000, for the win!\n")else$print("Sorry, need 75000\n")}catchproblem$print("Exception: ",problem,"\n")
prompt$ nekoc userinput.nekoprompt$ neko userinput.nEnter a line of text, then the number 75000this is a line of text:this is a line of text:75000Rosetta Code 75000, for the win!
usingSystem;usingSystem.Console;moduleInput{Main():void{Write("Enter a string:");_=ReadLine()mutableentry=0;mutablenumeric=false;do{Write("Enter 75000:");numeric=int.TryParse(ReadLine(),outentry);}while((!numeric)||(entry!=75000))}}
/* NetRexx */optionsreplaceformatcommentsjavacrossrefsymbolsnobinarycheckVal=75000say'Input a string then the number'checkValparseaskinStringparseaskinNumber.say'Input string:'inStringsay'Input number:'inNumberifinNumber==checkValthendosay'Success! Input number is as requested'endelsedosay'Failure! Number'inNumber'is not'checkValendreturn
(print"Enter an integer: ")(set'x(read-line))(print"Enter a string: ")(set'y(read-line))
importrdstdin,strutilsletstr=readLineFromStdin"Input a string: "letnum=parseInt(readLineFromStdin"Input an integer: ")
10 INPUT "ENTER A STRING: ",STRING$20 PRINT "YOU ENTERED ";STRING$;"."30 INPUT "ENTER AN INTEGER: ",INTEGER40 PRINT "YOU ENTERED";INTEGER;"."
{String: (input "Enter a string: ")Number: (input "Enter an integer: ")}Enter a string: Hello world!Enter an integer: 75000╭────────┬──────────────╮│ String │ Hello world! ││ Number │ 75000 │╰────────┴──────────────╯
MODULEInputText;IMPORTIn,Out;VARi:INTEGER;str:ARRAY512OFCHAR;BEGINOut.String("Enter a integer: ");Out.Flush();In.Int(i);Out.String("Enter a string: ");Out.Flush();In.String(str);ENDInputText.
use IO;bundle Default { class Hello { function : Main(args : String[]) ~ Nil { string := Console->GetInstance()->ReadString(); string->PrintLine(); number := Console->GetInstance()->ReadString()->ToInt(); number->PrintLine(); } }}print_string"Enter a string: ";letstr=read_line()inprint_string"Enter an integer: ";letnum=read_int()inPrintf.printf"%s%d\n"strnum
% read a string ("s")s=input("Enter a string: ","s");% read a GNU Octave expression, which is evaluated; e.g.% 5/7 gives 0.71429i=input("Enter an expression: ");% parse the input for an integerprintf("Enter an integer: ");ri=scanf("%d");% show the valuesdisp(s);disp(i);disp(ri);
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 ;Tested with Psion Series 3a & Series 5. source
PROC main: LOCAL s$(15),l& WHILE s$="" PRINT "Please enter a string." INPUT s$ IF s$="" PRINT "Nothing was entered. Please try again." PAUSE 60 CLS ENDIF ENDWH PRINT "Thank you! Yoe entered: ";s$ WHILE l&<>75000 PRINT "Please enter the number 75000." TRAP INPUT l& IF ERR=-1 PRINT PRINT "That's not a valid number. Please try again." PAUSE 60 CLS ELSEIF l&<>75000 PRINT "Wrong number. Please try again." PAUSE 60 CLS ENDIF ENDWH PRINT "Good job! You succesfully entered 75000!" GETENDP
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 ends=input();n=eval(input());
programUserInput(input,output);vari:Integer;s:String;beginwrite('Enter an integer: ');readln(i);write('Enter a string: ');readln(s)end.
##vars:=ReadString('Input a string:');varn:=ReadInteger('Input an integer:');
print"Enter a string: ";my$string=<>;print"Enter an integer: ";my$integer=<>;
?prompt_string("Enter any string:")?prompt_number("Enter the number 75000:",{75000,75000})
Enter any string:abc"abc"Enter the number 75000:123A number from 75000 to 75000 is expected here - try againEnter the number 75000:7500075000
/# Rosetta Code problem: https://rosettacode.org/wiki/User_input/Textby Galileo, 10/2022 #/"Enter any string: " input nltrue while 75000 "Enter the number " over tostr chain ": " chain input nl tonum over == notendwhiledrop pstack
Enter any string: HelloEnter the number 75000: 1000Enter the number 75000: 75000["Hello", 75000]=== Press any key to exit ===
#!/usr/bin/php<?php$string=fgets(STDIN);$integer=(int)fgets(STDIN);
main => print("Enter a string: "), String = read_line(), print("Enter a number: "), Number = read_int(), println([string=String,number=Number]).(in NIL # Guarantee reading from standard input (let (Str (read) Num (read)) (prinl "The string is: \"" Str "\"") (prinl "The number is: " Num) ) )
intmain(){write("Enter a String: ");stringstr=Stdio.stdin->gets();write("Enter 75000: ");intnum=Stdio.stdin->gets();}
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');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 valuesWrite "The string: " then the string to the console.Write "The number: " then the number to the console.
A sample run of the program:
Enter a string: abcEnter a number: 123The string: abcThe number: 123
io.write("Enter a number: ")a=io.read("*l")+0io.write("Enter a string: ")b=io.read("*l")
;;; Setup item readerlvars itemrep = incharitem(charin);lvars s, c, j = 0;;;; read chars up to a newline and put them on the stackwhile (charin() ->> c) /= `\n` do j + 1 -> j ; c endwhile;;;; build the stringconsstring(j) -> s;;;; read the integerlvars i = itemrep();
%open stdin for reading (and name the channel "kbd"):/kbd(%stdin)(r)filedef%make ten-char buffer to read string into:/buf(..........)def%read string into buffer:kbdbufreadline
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.
$string=Read-Host"Input a string"[int]$number=Read-Host"Input a number"
IfOpenConsole();DeclareastringandaintegertobeusedDefinetxt.s,num.iPrint("Enter a string: ")txt=Input()RepeatPrint("Enter the number 75000: ")num=Val(Input());ConvertstheInputtoaValuewithVal()Untilnum=75000;Checkthattheuserreallygivesus75000!Print("You made it!")Delay(3000):CloseConsole()EndIf
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: ")
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.
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, becauseusers, eh.
$ "Please enter a string: " inputsay 'You entered: "' echo$ say '"' cr cr $ "Please enter an integer: " inputtrim reverse trim reverse$->n iff [ say "You entered: " echo cr ]else [ say "That was not an integer." cr drop ]
Please enter a string: 3-ply sisal twineYou entered: "3-ply sisal twine"Please enter an integer: 75000You entered: 75000
stringval <- readline("String: ")intval <- as.integer(readline("Integer: "))#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)
(formerly Perl 6)
my $str = prompt("Enter a string: ");my $int = prompt("Enter a integer: ");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 onlineLanguage Examples.
'Input a string: ' print expect as str'Input an integer: ' print expect 0 prefer as num
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: ksldfPlease enter a string, and the number 75000:string:number: 75000Please enter a string, and the number 75000:string: Slert...number: 75000Thank you. Your string was 'Slert...'.
n: ask "Please enter # 75000: " str: ask "Please enter any string: "
: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 ;Note: all of the following would be accepted as being numerically equal to 75000:
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. */
see "Enter a string : " give s see "Enter an integer : " give i see "String = " + s + nlsee "Integer = " + i + nl
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
≪"Enter text" { "" 𝛼 } INPUT@ Set keyboard alpha mode75000 → string n75000 ≪DO"Enter number " n +"" INPUTUNTIL n →STR ==END string number≫ ≫ 'TASK' STO
print "Enter a string: "s = getsprintf "Enter an integer: "i = gets.to_i # If string entered, will return zeroprintf "Enter a real number: "f = Float(gets) rescue nil # converts a floating point number or returns nilputs "String = #{s}"puts "Integer = #{i}"puts "Float = #{f}"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)}print("Enter a number: ")val i=Console.readLong // Task says to enter 75000print("Enter a string: ")val s=Console.readLineTheread 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)
$ 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;Using theread(Type) built-in function:
var s = read(String);var i = read(Number); # auto-conversion to a number
or using theSys.readln(msg) method:
var s = Sys.readln("Enter a string: ");var i = Sys.readln("Enter a number: ").to_i;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.
'Enter a number: ' display.a := stdin nextLine asInteger.'Enter a string: ' display.b := stdin nextLine.
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
output = "Enter a string:" str = trim(input) output = "Enter an integer:" int = trim(input) output = "String: " str " Integer: " intend
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"))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;
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") endend
print("Enter a string: ", terminator: "")if let str = readLine() { print(str)}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)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 0while {$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"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
This program leaves the requested values in the global variabless andinteger.
Prgm InputStr "Enter a string", s Loop Prompt integer If integer ≠ 75000 Then Disp "That wasn't 75000." Else Exit EndIf EndLoopEndPrgm
needs readline." Enter a string: " readline is-data the-string." Enter a number: " readline >number [ ." Not a number!" drop 0 ] ifFalse is-data the-numberthe-string type crthe-number . cr
$$ MODE TUSCRIPTLOOPASK "Enter a string": str=""ASK "Enter an integer": int=""IF (int=='digits') THENPRINT "int=",int," str=",strEXITELSEPRINT/ERROR int," is not an integer"CYCLEENDIFENDLOOP
Output:
Enter a string >aEnter an integer >a@@@@@@@@ a is not an integer @@@@@@@@Enter a string >aEnter an integer >1int=1 str=a
&sc⋕&sc
#!/bin/shread stringread integerread -p 'Enter a number: ' numberecho "The number is $number"
## user input## in ursa, the type of data expected must be specifieddecl string strdecl int iout "input a string: " consoleset str (in string console)out "input an int: " consoleset i (in int console)out "you entered " str " and " i endl console
Public Sub text() Debug.Print InputBox("Input a string") Debug.Print InputBox("Input the integer 75000", "Input an integer", 75000, Context = "Long")End SubGet_Input(1, "Enter a string: ")#2 = Get_Num("Enter a number: ")Platform:.NET
Dim i As IntegerConsole.WriteLine("Enter an Integer")i = Console.ReadLine()Dim i As IntegerDim iString As StringConsole.WriteLine("Enter an Integer")iString = Console.ReadLine()Try i = Convert.ToInt32(iString)Catch ex As Exception Console.WriteLine("This is not an Integer")End TryDim i As StringConsole.WriteLine("Enter a String")i = Console.ReadLine()import osfn main() { s := os.input('Enter string').int() if s == 75000 { println('good') } else { println('bad') }}import osimport strconvfn main() { s := strconv.atoi(os.input('Enter string')) ! if s == 75000 { println('good') } else { println('bad $s') }}print 1 "Enter a string."input string$print 1 "Enter an integer."input integer
import "io" for Stdin, Stdoutvar stringwhile (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 numberwhile (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)")Enter a string : Rosetta CodeEnter a number : 75000You entered: string: Rosetta Code number: 75000
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." ) ) )
Enter a string: Rosetta CodeYes, "Rosetta Code" is a string.Now enter the integer 75000: 75000Yes, that is the integer 75000.
When the ChIn(0) intrinsic is first called, it collects characters fromthe keyboard until the Enter key is struck. It then returns to the XPL0program 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 inplace of the Enter key to mark the end of the string.
string 0; \use zero-terminated strings, instead of MSb terminatedinclude 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 stringText(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 BlaneyHowdy Loren Blaney! Now please enter "75000": 7500075000
str:=ask("Gimmie a string: ");n:=ask("Type 75000: ").toInt();10 INPUT "Enter a string:"; s$20 INPUT "Enter a number: "; n