何かキーを押すと続行します


36

あなたの仕事は、次のテキストを表示するプログラムを作成することで、ユーザーがキーを押すのを待つが(それはのようなキーを無視しても大丈夫ですctrlaltcaps lockキーは好きなように、など、限りlettersnumberssymbols、とenter無視されていない)を、その後、プログラムを終了します。

Press any key to continue... 

末尾の改行が許可されます。プログラムは、キーが押された直後に終了する必要があります。また、プログラムはかなり移植可能でなければなりません(つまり、OS固有のヘッダーやモジュールがなく、IDEの外部で実行されるなど)。


末尾の改行が避けられない場合を除き、プロンプトは上記のとおりでなければなりません。


これはであるため、バイト単位の最短回答が優先されます。これは私の最初のコードゴルフの質問でもあるので、PPCGのルールがわからない場合は謝罪します。


4
出力テキストの大文字と小文字は区別されますか?WinBatch PAUSEは有効な答えでしょうか(省略記号はから...に広がっています. . .)?
FlipTack

13
また、私はすべての答えを受け入れる前の週または2を待っていることをお勧めしたい
KritixiのLithos

3
ほとんどの言語のpause機能は、おそらくCaps-LockやControl(独自に押された)などのキーには反応しません。おそらく、プログラムがこれらのキーに気付かないことを許可するかどうかを明確にする必要があります
ルイスメンドー

15
数週間待ってから回答を受け入れる必要があります。数え切れないほどの人からアドバイスがあります(
ただし

12
@JungHwanMin私は他の人に同意します。エントリはに転がり停止したまで溶液を受け入れるために待ってください、私は本当に評判のローラーコースターに乗って楽しんでいない。
Suever

回答:



20

バッチ、46バイト

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

なぜならpause、出力にはそれぞれの前にスペースが含まれているから.です。


5
素敵なリダイレクト。たとえば、出力を送信してもらえますxか?次にx、テキストを保持するファイルが作成されますPress any key to continue . . .。2バイト節約しますが、それがこの課題に反するのか、それとも標準的な抜け穴に反するのかはわかりません。
steenbergh

私はchoice.exeフリーのシステムをしばらく使用していますが、@choice /n /m Press any key to continue...数十年前にも可能だったと感じています。
マナトワーク

選択のデフォルト値はJおよびNであるため、正しく覚えていればJまたはNが押されたときにのみプログラムが続行します。
geisterfurz007停止この混沌

@ geisterfurz007また、デフォルト値はローカライズされています。たとえば、私にとってchoicechoice /c SN(ポルトガル語のsim(yes)およびnão(no)の場合)と同等です。
イスマエルミゲル

ああ、あなたは正しい、@ geisterfurz007。今では、アルファベット全体が列挙されているバッチファイルがどれほど愚かに見えたかを覚えています。わかりました、それからこれは死んだ考えでした。
マナトワーク

15

HTML + JavaScript(ES6)、36 + 25 = 61バイト

JavaScriptプログラムを本当に終了することはできないので、Webページをクリアすることを考えるのが最善です。

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


HTML + JavaScript(ES6)、33 + 28 = 61バイト

にリダイレクトする@LarsWによって提案された代替ソリューションabout:blank

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


HTML / JavaScript、60バイト

@Ismael Miguelによる、スタンドアロンJSを使用しない別の素晴らしいソリューション。1バイト保存されました!

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


HTML + JavaScript(ES6)、26 + 28 = 54バイト

@George Reithによるドキュメント書き込みを利用したさらに別のソリューション。

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

HTML + JavaScript(ES7)、23 + 28 = 51バイト

提案されたES7バインド演算子を使用した同じプログラム:

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


これらのソリューションのほとんどは私自身のものではないので、礼儀正しくしてコメントで投票してください!


10
36 + 25は61ですか、何か不足していますか?

2
@ LarsW、ckjbgamesさて、チャンスは何ですか?書くまで知らない!;)
darrylyeo

2
<html onkeyup=this.innerHTML=''>Press any key to continue...<-60バイト。上でそれを試してみてくださいjsfiddle.net/xhb69401(それは両方で動作<html>し、<body>
イスマエルミゲル

2
ドキュメントをクリアするより短い方法で、アンカーは必要ありません。54バイトの総計のために。onkeyup=_=>document.open()Press any key to continue...
ジョージリース

2
また、es-nextで提案されているバインド演算子を使用すると、に削減できますonkeyup=::document.open
ジョージリース

14

MATL、35バイト

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

説明

'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 good catch
Suever

2
一方、Y.そうでもありません。たぶん、OPは明確にする必要があります。ControlやCaps-Lockなどのキーは、ほとんどのソリューションで失敗します
ルイスメンドー

1
@LuisMendoコントロールキー、
Caps Lock

@LuisMendoあなたの変更にはエンターキーは必要ないでしょうか?または多分私はそれを間違って覚えている
スーバー

@Sueverああ、もちろん!入力が必要です
ルイスメンドー

11

TI-Basic、55バイト

基本的に、キーが押されるまでループします。あまりにも悪い小文字は、TI-Basicでそれぞれ2バイトです...

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

PSこの仕組みの説明については、@ GoldenRatioのコメントを参照してください。天才です!


まず、バイトカウントは現在オフになっており、実際には55バイトです(TI-84 +でプログラムを作成し、テストしたばかりです)。第二に、これは技術的には有効ではありません。キーを押して続行します...代わりに15文字にカットされます...代わりに、バイト数を保持して、2つのdispコマンドにします。:Disp "Press any(忘れないでください:コードではカウントします)そしてDisp "key to continuesin((罪は1バイトで...を強制して新しい行とdispを補います。これによりキーとキーの間のスペースが節約されます)
黄金比

私が考えた最初の言語、これに私を打ち負かしてください。
Cアンダーソン

先端@GoldenRatioためのおかげで、私は思考だったと思いますgetKey、それは実際には1だとき、私はと仮定2つのバイトだったText(か、Output(あなたはすべて1行でそれを合うことができます。しかし、あなたの提案は優れています。行末で暗黙の省略記号を使用することは考えていませんでした。改めて感謝します。編集します。
ティムテック

それを更新するためのThx、そしてバイトを節約することはないので、dispをコンマで使用することは最終的に正当な理由があると思います。私は通常、明確なボタンを押す傾向があるため、それらを別々の行に配置します:D。また、サイズを採点する方法の公式方法はありますか?つまり、プログラム名としてカウントしなかった9バイトカウントすべきでしょうか?また、削除できない開始コロンの1バイトはカウントする必要がありますか?私はスペースを見つけるためにプログラムサイズのために10を引くことに慣れているので、0バイトとしてそれをマークしましたが、多分コロンがカウントされるべきです。
黄金比

いいえ、基本的に完全に空のプログラムを作成すると、0バイトとカウントされ、そこから開始します。これは、ソースファイルのファイル名をカウントするようなものです。また、先頭のコロンは単なる表示用であり、実際にはプログラムの一部ではありません。実際、すべての改行は、計算機のエディターにコロンを自動的に表示しますが、これも表示専用です(cemetechソースコーダーを試して、意味を確認してください)。最後に、Disp2行以上に分割しても分割しなくても、バイトカウントは同じです(ただし、常にこのようになっているわけではありません)。
ティムテック

8

バッシュ、 46 43 42バイト

@DigitalTraumaのおかげで1バイト節約

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

read組み込みを使用します。-rユーザーがエスケープを入力できないようにします。-n 11文字のみ使用できます。-pプロンプトです


<cr>を
押す

@ GlennRanders-Pehrsonあなたのbashがをサポートしていない場合、それが起こると思います-n 1。ただし、エンターキーを押さずに機能します(v3.2.57)およびデバインマシン(v4.3.30)
Downgoat

私は引用符( ")と入力した場合にも動作しません
グレン・ランダース-Pehrson

1
行をファイル(anykey.sh)に入れて実行すると正常に動作します。「-rn」と「1」の間のスペースを削除しても正常に動作します。
グレンランダース-パーソン

1
-rn11バイト節約
デジタル外傷

8

Haskell51 50バイト(@ villou24に感謝)

main=putStr"Press any key to continue...">>getChar

オンラインでお試しください!


6
エンターを待ちます。getChar代わりに使用できます。
クリスチャンシーバーズ

1
putStr文字列との間のスペースを削除することで、バイトを節約できます。
-villou24

回答者に自分の投稿@ckjbgamesを編集させてください。彼のためにそれをしないでください
-MildlyMilquetoast


4

QBasic( QB64)、37(42?)バイト

残念ながら、QBasicに組み込まれているプログラム終了プロンプトには省略記号がないため、自分で印刷する必要があります。

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

SLEEP引数なしでキーを押すまで待機します。)

このコードは、質問が文字通り求めるものを実行しますが、もちろんQBasicは「続行するには任意のキーを押してください」と表示し、キーを押してからIDEに戻るため、質問の精神に合っているようには見えません。+5バイトの場合、IDEに直接アクセスするものを次に示します。

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

STOPデバッグ文です。通常のQBasicでは、ブレークポイントを設定します。実行が停止し、IDEに戻りますが、F5で実行を再開できます。それがプログラムの「終了」としてカウントされるかどうかは不明です。ただし、ブレークポイントを実行できないQB64エミュレーターを使用しています。に遭遇するとSTOP、単に停止します-冗長な「任意のキーを押してください」というメッセージなしでIDEに直接戻ります。


奇妙なことに、スタンドアロンのQB64 exeを実行すると、「続行するには任意のキーを押してください」というメッセージも表示されます。私はLOCATEそれ以降のドットを印刷するために使用しようとしましたが、QBasicはこのメッセージを印刷するときに一番下の行全体をクリアします
...-steenbergh

4

処理、89 81バイト

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

説明

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

プログラムで複数の関数を使用しているため、これは必須です。内部のsetup()すべて、この場合はstringが呼び出されます"Press any key to continue..."

if(key>0)exit();

keykey最後に押されたキーのint値が常に含まれます)が0(nullバイトでない)より大きいかどうかをチェックします。条件が満たされると、プログラムは終了します。

void draw(){}

draw() プログラムが開始すると停止するのではなく、プログラムが常にキーを探し続けるようにします。

(Javaに似た言語のビルトインがまだ冗長であると感じる...)


私はしていない、本当に処理を知っているが、私はあなたが交換することができるはずだと思うvoid steup(){...}static{...}
パベル

2
@Pavelいや、ない仕事
KritixiのLithos

4

パスカル、75 65バイト

これは、Free Pascal Compilerバージョン3.0.0でテストされました。
TurboPascal 7以降で動作する場合があります。

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

悲しいことに、私は置き換えることはできませんreadkeyreadln挑戦をすることを必要とするので、いずれかのキーが受け入れられます。


私はこのコードをhttp://rextester.com/l/pascal_online_compilerでテストしました。入力の有無にかかわらず。
予想どおり、プログラムは、発生しないキー入力を待機しているため、10秒後に終了します。


@manatworkに、間違っていることを証明して10バイトを節約してくれたことに感謝しますprogram _;


FreePascalもTurboPascalもprogramキーワードの使用を必要としません。(実際には、そのような古代の実装に出会ったことは一度もありませんでした。)
マナトワーク

@manatwork私はなしprogramでそれを試してみましたが、それは不平を言いました。また、私は時々TurboPascalを使用します。それが必要です(注意:requireprogram。を使用せずに実行できる場所をテストできる場所を知っている場合はprogram、削除します。私はそこにいるのが嫌いです。そしてそれuses Crt;
イスマエルミゲル

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)

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.