premere un tasto qualsiasi per continuare


36

Il vostro compito è quello di creare un programma che visualizza il seguente testo, attendere che l'utente prema un tasto (è bene ignorare tasti come ctrl, alt, caps lock, ecc, fino a quando tasti come letters, numbers, symbols, e enternon sono ignorati), e quindi terminare il programma:

Press any key to continue... 

Sono consentite nuove righe finali. Il programma deve uscire immediatamente dopo aver premuto un tasto. Inoltre, il programma deve essere abbastanza portatile (ovvero senza intestazioni o moduli specifici del sistema operativo, eseguito al di fuori di un IDE, ecc.).


Il prompt deve essere esattamente come mostrato sopra, a meno che una nuova riga finale non possa essere evitata.


Questo è , quindi vince la risposta più breve in byte. Questa è anche la mia prima domanda sul code-golf, quindi mi scuso se non conosco le regole su PPCG.


4
Il testo di output fa distinzione tra maiuscole e minuscole? WinBatch PAUSEsarebbe una risposta valida (i puntini di sospensione sono sparsi da ...a . . .)?
FlipTack

13
Suggerirei anche di aspettare una settimana o due prima di accettare qualsiasi risposta
Kritixi Lithos il

3
La maggior parte delle pausefunzioni del linguaggio sono probabilmente insensibili a tasti come Caps-Lock o Control (premuto da solo). Forse dovresti chiarire se al programma è permesso non notare quelle chiavi
Luis Mendo il

15
Dovresti aspettare qualche settimana prima di accettare una risposta, come innumerevoli altri ti hanno consigliato (eppure hai scelto di ignorare il loro consiglio)
FlipTack

12
@JungHwanMin Sono d'accordo con gli altri. Per favore attendi di accettare una soluzione fino a quando le iscrizioni non avranno smesso di
entrare

Risposte:


5

SmallBasic, 18 17 byte

  • Versione 2.0

17 byte

TextWindow.Show()
  • Versione 1.0

18 byte

TextWindow.Pause()

3
Non potresti farlo anche tu TextWindow.Show()? Basato su questo sito che dovrebbe avere lo stesso effetto.
Suever,

20

Lotto, 46 ​​byte

@echo Press any key to continue...
@pause>nul

Perché pausel'output contiene uno spazio prima di ciascuno ..


5
Bel reindirizzamento. Potresti anche inviare l'output a, diciamo x,? Quindi xverrà creato un file che contiene il testo Press any key to continue . . .. Salva 2 byte, ma non sono sicuro che ciò vada contro questa sfida o eventuali scappatoie standard.
steenbergh,

Sono sul sistema libero choice.exe da un po ', ma ho la sensazione che @choice /n /m Press any key to continue...fosse possibile anche alcuni decenni fa.
arte

La scelta ha valori predefiniti come J e N, quindi il programma andrebbe avanti solo quando si preme J o N se ricordo correttamente.
geisterfurz007 Ferma questo caos il

@ geisterfurz007 Inoltre, il valore predefinito è localizzato. Ad esempio, per me choiceequivale a choice /c SN(per sim(sì) e não(no) in portoghese).
Ismael Miguel,

Ah, hai ragione, @ geisterfurz007. Ora ricordo quanto erano stupidi i miei file batch con l'intero alfabeto elencato. Ok, allora questa era un'idea morta.
arte

15

HTML + JavaScript (ES6), 36 + 25 = 61 byte

Non puoi davvero uscire da un programma JavaScript, quindi cancellare la pagina web è la migliore che mi venga in mente.

onkeyup=_=>a.innerHTML=''
<a id=a>Press any key to continue...


HTML + JavaScript (ES6), 33 + 28 = 61 byte

Soluzione alternativa suggerita da @LarsW che reindirizza a about:blank.

onkeyup=_=>location='about:blank'
Press any key to continue...


HTML / JavaScript, 60 byte

Un'altra fantastica soluzione di @Ismael Miguel che non utilizza JS autonomo. 1 byte salvato!

<html onkeyup=this.innerHTML=''>Press any key to continue...


HTML + JavaScript (ES6), 26 + 28 = 54 byte

Ennesima soluzione di @George Reith che utilizza la scrittura di documenti.

onkeyup=_=>document.open()
Press any key to continue...

HTML + JavaScript (ES7), 23 + 28 = 51 byte

Stesso programma con l' operatore di bind ES7 proposto :

onkeyup=::document.open
Press any key to continue...


Poiché la maggior parte di queste soluzioni non sono le mie, fai una cortesia e votale nei commenti!


10
36 + 25 è 61 o mi sto perdendo qualcosa?

2
@LarsW, ckjbgames Bene, quali sono le possibilità? Non lo sai mai fino a quando non lo scrivi! ;)
darrylyeo,

2
<html onkeyup=this.innerHTML=''>Press any key to continue...<- 60 byte. Provalo su jsfiddle.net/xhb69401 (funziona con entrambi <html>e <body>)
Ismael Miguel

2
Modo più breve per cancellare il documento e non necessita di ancoraggio. onkeyup=_=>document.open()con Press any key to continue...un totale complessivo di 54 byte.
George Reith,

2
Anche con l'operatore di bind proposto es-next potrebbe essere ridotto a onkeyup=::document.open.
George Reith,

14

MATL, 35 byte

'Press any key to continue...'D0$Y.

Spiegazione

'Press any key to continue...'      % String literal
D                                   % Display the string (has trailing newline)
0$Y.                                % Pause until the user presses any key

@LuisMendo Ah buona cattura
Suever

2
D'altra parte, Y.neanche. Forse l'OP dovrebbe chiarire. Tasti come Control e Caps-lock falliranno nella maggior parte delle soluzioni
Luis Mendo il

1
@LuisMendo Va bene perdere i tasti di controllo, il blocco maiuscole, ecc.
ckjbgames

@LuisMendo La tua modifica non richiederebbe una chiave di invio? O forse me lo ricordo male
Suever il

@Suever Oh, certo! Invio richiesto
Luis Mendo,

11

TI-Basic, 55 byte

Fondamentalmente, scorre fino a quando non viene premuto un tasto. Poche lettere minuscole sono due byte ciascuna in TI-Basic ...

Disp "Press any","key to continuesin(
Repeat getKey
End

PS Vedi il commento di @GoldenRatio per la spiegazione di come funziona. È geniale!


Prima di tutto, il conteggio dei byte è attualmente disattivato, ovvero 55 byte (appena creato un programma su TI-84 + e testato). In secondo luogo, questo tecnicamente non è valido, perché non viene visualizzato Premere alcun tasto per continuare ... e invece taglia a 15 caratteri più ... Invece, preservando il conteggio dei byte, esegui due comandi disp. :Disp "Press any(non dimenticare: nel tuo codice, conta) e Disp "key to continuesin((Il peccato impone un ... in 1 byte per compensare la nuova riga e disp, e questo fa risparmiare uno spazio tra qualsiasi e chiave)
Golden Ratio

Sconfiggimi in questa prima lingua a cui ho pensato.
C Anderson,

Grazie per il suggerimento @GoldenRatio, immagino che stavo pensando a getKey2 byte quando in realtà è 1. Suppongo Text(o Output(potresti adattarlo tutto su una riga. Ma il tuo suggerimento è migliore. Non ho pensato di usare le ellissi implicite alla fine di una linea. Grazie ancora, lo modificherò ora.
Timtech,

Grazie per averlo aggiornato, e immagino che usare disp con una virgola abbia finalmente un buon motivo, dal momento che non ha mai salvato i byte. Di solito li metto su linee separate a causa della mia tendenza a premere il pulsante Clear: D. Inoltre, esiste un metodo ufficiale per ottenere il punteggio? Con questo voglio dire, i 9 byte che non ho contato per un nome di programma dovrebbero contare? E dovrebbe valere il 1 byte per i due punti iniziali che non possono essere eliminati? L'ho contrassegnato come 0 byte, perché per trovare spazio sono abituato a sottrarre 10 per la dimensione del programma, ma forse i due punti dovrebbero contare.
Rapporto aurea

No, fondamentalmente se si crea un programma completamente vuoto conta 0 byte, quindi si inizia da lì. Sarebbe come contare il nome file di un file sorgente. Inoltre, i due punti iniziali sono solo per lo spettacolo e in realtà non fanno parte del programma. In effetti, ogni newline mostra automaticamente i due punti nell'editor sulla calcolatrice, ma di nuovo, questi sono solo per lo spettacolo (prova cemetech sourcecoder per vedere cosa intendo). Infine, il bytecount è lo stesso sia che dividiamo le Dispdue righe o meno (ma non è sempre così).
Timtech,

8

Bash, 46 43 42 byte

Salvato 1 byte grazie a @DigitalTrauma

read -rn1 -p"Press any key to continue..."

Utilizza il readbuilt-in. -rsi assicura che non consenta all'utente di inserire escape. -n 1consente solo un personaggio. -pè il prompt


Non continua fino a quando non ho colpito un <cr>
Glenn Randers-Pehrson il

@ GlennRanders-Pehrson Credo che ciò possa accadere se il tuo bash non supporta -n 1. Funziona senza premere invio per me (v3.2.57) e sulla mia macchina debain (v4.3.30)
Downgoat

Inoltre non funziona se scrivo una citazione (")
Glenn Randers-Pehrson il

1
Funziona bene se inserisco la riga in un file (anykey.sh) e lo eseguo. Funziona bene anche se rimuovo lo spazio tra "-rn" e "1".
Glenn Randers-Pehrson,

1
-rn1salva 1 byte
Trauma digitale il



4

QBasic (QB64), 37 (42?) bytes

Unfortunately, QBasic's built-in end-of-program prompt doesn't have the ellipsis, so we'll have to print it ourselves:

?"Press any key to continue..."
SLEEP

(SLEEP without an argument waits until a keypress.)

This code does what the question literally asks for, but it doesn't seem like it fits the spirit of the question because, of course, QBasic then displays "Press any key to continue" and waits for a keypress before returning to the IDE. Here's one that goes straight to the IDE, for +5 bytes:

?"Press any key to continue..."
SLEEP
STOP

STOP is a debugging statement. In regular QBasic, it sets a breakpoint: execution halts and we return to the IDE, but execution can be resumed again with F5. It's unclear whether that would count as the program "exiting." However, I'm using the QB64 emulator, which can't do breakpoints. Upon encountering STOP, it simply halts--returning straight to the IDE without the redundant "Press any key" message.


Oddly enough, the 'Press any key to continue' also shows up when executing a standalone QB64 exe. I tried to use LOCATE to just print the dots after it, but QBasic clears the entire bottom row when it prints this message...
steenbergh

4

Processing, 89 81 bytes

void setup(){print("Press any key to continue...");}void draw(){if(key>0)exit();}

Explanation

void setup(){print("Press any key to continue...");}

This is required since I am using more than one function in my program. Anything inside setup() gets called, in this case the string "Press any key to continue...".

if(key>0)exit();

Checks if key (key will always contain the int value of the last key pressed) is more than 0 (ie not a null byte). If the condition is satisfied, then the program exits.

void draw(){}

draw() ensures that that the program will always keep looking for a key instead of stopping once the program starts.

(That feel when a builtin in a Java-like language is still verbose...)


I don't really know Processing, but I think you should be able to replace void steup(){...} with static{...}
Pavel

2
@Pavel Nope, doesn't work
Kritixi Lithos

4

Pascal, 75 65 bytes

This was tested with the Free Pascal Compiler, version 3.0.0.
It may work with TurboPascal 7 or newer.

uses Crt;begin write('Press any key to continue...');readkey;end.

Sadly, I can't replace readkey with readln since the challenge requires that any key be accepted.


I've tested this code on http://rextester.com/l/pascal_online_compiler, with and without supplying an input.
As expected, the program is terminated after 10s, since it sits waiting for a keypress that never happens.


Thanks to @manatwork for saving me 10 bytes by proving me wrong, and showing that I don't need the program _;.


Neither FreePascal nor TurboPascal requires the use of program keyword. (Actually I never met such ancient implementation that did.)
manatwork

@manatwork I tried it without program and it complained. Also, I sometimes use TurboPascal. That one requires (notice: requires) the program there. If you know any place I can test where it runs without the program, I will remove it. I hate having it there. And that uses Crt;.
Ismael Miguel

1
I don't get you. It works fine including the rextester service you linked. In my command line: pastebin.com/pVr9dqxd
manatwork

@manatwork You're right. I know why it complained: I wrote program; instead of actually removing that bit. Thanks for alerting me to that.
Ismael Miguel

4

Scratch, 81 bytes

image

when gf clicked
say [Press any key to continue...
wait until <key [any v] pressed

(Scratchblocks link)

If you wanted it to stop the entire program when you pressed a key (including other threads) you'd have to add a stop all. If you want to get rid of the say dialog you need an empty say block (stop all works as well).

Convenient that Scratch has a builtin for this!


4

Bash 48 44 42 bytes

read -rn1 -p"Press any key to continue..."

@mame98 Thanks for saving 4 bytes.

@RaisingAgent Thanks for saving 2 bytes.


You can improve this by adding up the flags, like read -srn1 -p".." and remove the last space in the promt quote. Also, I'm not sure if you need the 's' flag
mame98

1
remove the last space in the quotes _ & -s
RaisingAgent

@RaisingAgent Thanks, updated :)
Abel Tom

3

R, 56 bytes

cat('Press any key to continue...');keypress::keypress()

This works in Linux and OSX terminals.


3

Ruby (2.3) (+ Batch), 52 55 54 53 46 bytes

Now 46 bytes thanks to Alexis Andersen.

Note: Tested on Windows, might not work if there is no pause command.

puts"Press any key to continue...";`pause>nul`

Explanation

Puts the required text:

puts"Press any key to continue..."

End the line:

;

Run the Batch pause command and pipe output to nul:

`pause>nul`

Hello, welcome to PPCG. I see that you have a list of edits in the body of your submission. While this may be customary on other sites, since anyone can see the edit history of a post, we generally leave the history of the post out of the body (aside from the strike throughs for byte counts). This seems like a good first golf and I hope you have fun here.
Wheat Wizard

@WheatWizard Thanks, should I leave the edits there or remove them?
notme1560

1
I think that it makes for a much more readable answer if you remove them and I would personally recommend doing so.
Wheat Wizard

you can shorten that by replacing system with backticks: ` pause>nul ` or even shorter, just use gets (also, there's no good way to include a backtick in a code block in a comment)
Alexis Andersen

@AlexisAndersen doesn't gets wait for enter, and not just any key?
notme1560

3

Java, 127 bytes

class P{public static void main(String[]a)throws Exception{System.out.print("Press any key to continue...");System.in.read();}}

Note: the console must be set to raw mode in order for this to work.


Then I'm afraid your code should set the console so, like original.legin's Perl solution does.
manatwork

@manatwork Also, the program must be fairly portable (i.e no OS-specific headers or modules, runs outside of an IDE, etc.) if you follow that SO link there is no OS-independent way to do this. Meaning, the answer you linked is equally as valid as this one.

3

SmileBASIC, 52 bytes

?"Press any key to continue...
WHILE""==INKEY$()WEND

3

Python 2, 110 bytes

import curses as c
s=c.initscr()
c.cbreak()
s.addstr(0,0,'Press any key to continue...')
while not s.getch():1

2

Mathematica, 62 bytes

EventHandler["Press any key to continue...","KeyDown":>Exit[]]

Explanation

EventHandler["Press any key to continue...","KeyDown":>Exit[]]
EventHandler[                                                ]  (* Create a new EventHandler *)
             "Press any key to continue..."                     (* Print the dialog text *)
                                            "KeyDown":>Exit[]   (* When a key is pressed down, exit *)

2

SmileBASIC, 55 bytes

?"Press any key to continue..."@L IF INKEY$()!=""GOTO@L

Explained:

?"Press any key to continue..."  '? means PRINT
@L                               'start of loop
IF INKEY$()!="" GOTO @L          'if no key pressed goto @L

WHILE""==INKEY$()WEND is smaller
12Me21

2

Python 2/3 POSIX, 85 bytes

import sys,tty
print('Press any key to continue...')
tty.setraw(1)
sys.stdin.read(1)

2

Python 3, 65 bytes

Requires the Windows version of Python.

from msvcrt import*
print("Press any key to continue...")
getch()

msvcrt.getch() doesn't wait for the enter key to be pressed like input(), it returns the first key pressed.

Python Docs for msvcrt.getch(): https://docs.python.org/3/library/msvcrt.html#msvcrt.getch

Thanks to @Fliptack for saving some bytes


This answer is invalid without an import msvcrt somewhere
FlipTack

2
As this is code-golf you should remove the comments from your code. Also, using from msvcrt import* appears to be 1 byte shorter
FlipTack

cool, thx @FlitTack
Zachary Smith

2

Node.js, 102 101 99 bytes

with(process)stdout.write('Press any key to continue...'),s=stdin,s.setRawMode(1),s.on('data',exit)

Not much gain, just 1 character shorter with with: pastebin.com/BhrAyq2K
manatwork

@manatwork Nice one! First time with has saved me bytes (or byte)
George Reith

1
Now you can remove the curly brackets and replace line breaks with commas for 2 more bytes.
darrylyeo

Also if I'm not mistaken, stdout.write`Press any key to continue...` will save 2 bytes in ES6.
darrylyeo

@darrylyeo Commas work thats awesome thanks! Unfortunately a tagged template literal can't be used here as it actually passes in an array and process.stdout.write doesn't do implicit conversions to string (it just errors).
George Reith

2

Sinclair ZX81/Timex TS1000 BASIC: Method 1 approximately 41 bytes

1 PRINT "PRESS ANY KEY TO CONTINUE..."
2 GOTO (INKEY$<>"")+VAL "2"

Method 2 approximately 38 BYTES

1 PRINT "PRESS ANY KEY TO CONTINUE..."
2 PAUSE VAL "4E4"

I prefer method 1 as on the ZX81, there is a screen flicker when PAUSE is called, and if you want long enough (providing the ZX81 doesn't overheat or crash) the pause will eventually come to an end, whereas method 1 is stuck in an infinite loop until a key is pressed, and no screen flicker.

I'll work out the correct number of bytes used later when I have the right bit of BASIC that will tell me. By the way, using VAL "x" instead of the number saves valuable RAM on a ZX81 (I think that this is the same for the ZX Spectrum as well).


Both methods will work on the Sinclair ZX Spectrum as well, the advantage being that the Spectrum has upper and lower case letters, whereas the ZX81 does not by default (and doesn't have a single quote either as a standard character).
Shaun Bebbers

Method 2 on the Sinclair ZX Spectrum could be condensed to 1 PRINT "Press any key to continue...": PAUSE 4e4
Shaun Bebbers

1
PAUSE 0 pauses for ever.
Neil

Yes I've not programmed in Sinclair Spectrum BASIC for so long that I forgot about that. PAUSE 0 in ZX81 BASIC does not pause forever.
Shaun Bebbers

1

Perl 5, 79 bytes

system "stty cbreak";$|=1;print "Press any key to continue...";read(STDIN,$a,1)

used as:

perl -e 'system "stty cbreak";$|=1;print "Press any key to continue...";read(STDIN,$a,1)'

No prizes of course. I'm sure some perl person will have a better way.

(89 bytes if the interpreter invocation as well needs to be included in the count)


@Pavel, he counted system in his bytecount, so I don't know what you meant with that comment.
Dada

1
@original.legin I think Perl won't do much better than this. A few bytes you can golf still: $|=1 isn't necessary, you have a space after print, you can drop the parenthesis around the arguments of read, you can use backticks instead of system, and finally, print returns 1, so you can use it instead of the litteral 1 in the call to read. So in the end, we get: perl -e '`stty cbreak`;read STDIN,$a,print"Press any key to continue..."'
Dada

@Dada You can also shave off 2 bytes with say, although I think this approach fails the "portable" requirement. The best portable solution I can find is perl -MTerm::ReadKey -E'say"Press any key to continue...";ReadMode 3;ReadKey' (52 bytes + 16 bytes for -MTerm::ReadKey<space>). Be careful, this will screw up your terminal unless you restore the read mode at the end with ReadMode 1.
ThisSuitIsBlackNot

1
@ThisSuitIsBlackNot Indeed, I didn't see that requirement about portability. About say, I tend not to use it anymore (I agree mostly with this meta post). Now back to a short code, IO::Prompt will be shorter than Term::ReadKey (40 + 13 = 53 bytes) : perl -MIO::Prompt -e 'prompt"Press any key to continue... ",-1'. And as it happens, it's even shorter than what I suggested in my previous comment.
Dada

1
@Dada I can see both sides of the -E argument. The last time I checked, though, J B's answer had been uncontested for four years, so that's what I've followed. Maybe I need to revisit it again. As for IO::Prompt, good find! Although it doesn't work on my Strawberry 5.20.2 on Windows, while Term::ReadKey does.
ThisSuitIsBlackNot

1

PHP, 73 bytes

echo"Press any key to continue...";$h=fopen("php://stdin","r");fgets($h);

Run it in the PHP interactive shell (php -a)


“The program must exit immediately after a key is pressed.” – This waits until Enter or blackout…
manatwork

1

C#, 101 bytes

using C=System.Console;class P{static void Main(){C.Write("Press any key to continue...");C.Read();}}

Tested on Linux, should run on any system having the .NET libraries and the Common Language Runtime.

Ungolfed program:

using C = System.Console; // creating a shorter alias for the System.Console class

class P
{
    static void Main()
    {
        C.Write("Press any key to continue...");    // prints the message
        C.Read();   // waits for key press
    }
}

CTRL, ALT, SHIFT are ignored. The pressed key will be echoed on screen if printable.

Echo can be disabled by replacing C.Read() with C.ReadKey(0<1) at the cost of 6 more bytes.


1

8th, 47 bytes

"Press any key to continue..." . cr con:key bye

This program ignores keys like ctrl, alt, caps lock. Quits with keys like letters, numbers, symbols, and enter.

Explanation

"Press any key to continue..." . cr \ Print message 
con:key                             \ Wait for key input from console  
bye                                 \ Quit program 

On Windows only you can save 3 bytes omitting cr
Chaos Manor

1

C#, 29 bytes

class P{static void Main(){}}

Not sure if this is considered valid because it prints:

Press any key to continue . . .

But there is a Batch answer that prints this as well.


1

Forth (gforth), 39 bytes

." Press any key to continue..."key bye

(Yes, there is already an 8th solution but this is shorter)

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.