답을 주장하다


31

런타임시에 대한 프롬프트 계속 입력 라인 (빈 줄 바꿈 제외) 사용자 입력 뭔가 때까지, 즉 눌러 단지 않습니다 Enter또는 OK. 출력이나 결과가 요구되거나 금지되지 않습니다.

의사 코드 1

myform = new form("GUI")
myform.mytxt = new editfield("")
myform.ok = new button("OK")
repeat
  waitfor(myform.ok,"click")
until myform.mytxt.content <> ""

의사 코드 2

LET TEXT = ""
WHILE TEXT = "" DO
  TEXT = PROMPT("")
ENDWHILE

실시 예 1

프로그램이 실행되고 단일 텍스트 필드와 OK버튼이 있는 양식이 즉시 나타납니다 .
사용자가 OK버튼을 클릭 합니다.
아무 반응이 없습니다.
사용자는 "hello world"를 텍스트 필드에 붙여 넣고 OK단추를 클릭 합니다.
프로그램이 종료됩니다.

실시 예 2

함수가 호출되고 즉시 빈 줄과 깜박이는 커서가 표시됩니다.
사용자가를 누릅니다 Enter.
커서가 한 줄 아래로 이동합니다.
사용자가를 누릅니다 Enter.
커서가 한 줄 아래로 이동합니다.
사용자가 누름 PPCGEnter
기능 반환.


공백 전용 줄을 비어있는 것으로 계산할 수 있습니까?
12431234123412341234123

@ 12431234123412341234123 No.
Adám

사용자가 데이터를 입력하기 시작하면 전체 라인을 기다려야합니까?
Matteo Italia

좋아, @CodyGray의 삭제 된 답변에 대한 의견에서 그것은 허용되지 않는 것 같습니다.
Matteo Italia

@MatteoItalia 그렇습니다. 입력 라인 .
Adám

답변:


16

TI-BASIC, 2 바이트

:Prompt X

TI-BASIC은이를 자동으로 수행합니다. 입력이 완료되면 종료됩니다.

GIF는 다음과 같습니다.

enter image description here

enterKey Press History (키 프레스 기록)에서 키 의 카운트를 확인하십시오 . 하여 만든 TI-SmartView CEezgif.com .


1
흠 .. 이것은 2 바이트입니까?
Geeky I

9
TI-BASIC은 토큰 기반 입니다.
Scott Milner

그리고 답을 위해 Enter가 필요하지 않습니까? 온라인으로 테스트 할 곳이 있습니까?
Adám

@ Adám 답변을 입력하지 않아도됩니다. 내가 아는 한, 이미 TI ROM 이미지가 없어도 온라인에 갈 수있는 곳은 없습니다. 그래도 집에 도착하면 .gif를 게시 할 수 있습니다.
Scott Milner

1
@ Adám 직접 ROM을 소유하지 않고 TI-BASIC을 온라인으로 테스트하는 것은 불법입니다.
아웃 골퍼 Erik



15

자바 스크립트, 37 22 17 바이트

while(!prompt());

while(!prompt());

설명

while키워드는 시작 while루프. 루프 상태 !prompt()에서 입력을 요청하고 입력 여부를 확인합니다. 그것이 주어지지 않으면, 루프 본문이 실행되며, 우리의 경우에는 비어 있으며, 인터프리터는 루프 조건으로 돌아갑니다. 사용자가 입력을 제공 할 때까지 동일한 프로세스가 계속 반복됩니다.


while(""==prompt(""));
Adám

@ Adám Wow. 솔루션을 더 작게 만드는 방법에 대해 생각하고 있었으므로 답을 얻었습니다.
Arjun

명백해 보였다. 그러나 내 브라우저 콘솔은 후행없이 실행을 거부하지만 ;초기 표현은없이 잘 작동합니다 ;. 왜 그런지 알아?
Adám

아니요, Chrome 따라서 모든 JavaScript 엔진이 현재 표현식의 생략을 처리 ;할 수 있으면 해당 바이트를 저장할 수 있습니다. :-)
Adám

1
@ Adám 소스 코드에서 세미콜론을 제거한 후 생성 된 오류의 실제 원인을 알아 냈습니다. 그 이유는 while 루프가 루프 조건 후 루프 본문으로 명령문 (또는 명령문 그룹)을 기대하기 때문입니다. 세미콜론을 추가하면 루프 본문이 끝났다고 생각합니다. 그러나 세미콜론을 제거하면 다음 명령문이 루프 본문으로 예상됩니다. 그러나 우리의 경우 루프 조건 뒤에 새로운 문장이 나오지 않습니다. 따라서 오류가 발생합니다. 나는 그것이 분명하기를 바랍니다. 나는 물건을 설명하는 데 끔찍하다!! : p
Arjun

9

자바, 55 바이트

void f()throws Exception{while(System.in.read()==10);}}

올바르게 기억한다면 (PPCG에서 활동한지 얼마되지 않아) 프로그램은 기능 일 수 있습니다.

이것은 시스템마다 다릅니다. 줄 끝 문자가 단일 줄 바꿈 인 시스템에서만 작동합니다. 행 끝 문자 대신 캐리지 리턴 경우, 교체 10와 함께 13. Windows에서는 Windows의 줄 끝이이므로 작동하지 않습니다 \r\n.

이것은에서 직접 읽을 수 있다는 사실을 이용합니다 System.in.


2
이 답변에 대해서만 환영합니다! : D
코너 오브라이언

3
@Justin으로 돌아온 것을 환영합니다!
Digital Trauma

1
활동할 계획이 없다. 여기저기서 질문을하세요
Justin

"Windows에서 작동하지 않습니다"문제를 피하기 위해 \r전체 문자열을 테스트하는 대신 첫 번째 문자 만 테스트하여 그 문자인지 확인한 다음 2 개의 EOL 문자가있는 문제가 발생합니까?
코디 그레이

@CodyGray 아니요. 한 번에 1 개의 문자를 읽습니다. 그것은 System.in당신이 직접 할 수있는 전부입니다. (음, 한 번에 문자 배열을 읽습니다.) 내 루프 본문 (빈)은 입력의 모든 문자에 대해 실행됩니다
Justin

9

HTML5, 33 22 바이트

<form><input required>

<form><input required>

설명

required속성 <input>은 값을 입력하지 않으면 브라우저가 사용자에게 "이 필드는 필수입니다"메시지 정렬을 알려줍니다. 그러나 값을 입력하면 값이 명시 적으로 값을 지정하지 않았기 때문에 action속성의 URL로 전송됩니다 <form>(이 경우 현재 파일 자체 임).

최신 버전의 Chrome (버전 55.0)에서 테스트되었습니다. 다른 브라우저 및 버전에서 작동 할 수 있습니다.


action=/ might work on some browsers.
Neil

1
You could probably ditch the action attribute altogether.
Shaggy

1
@Arjun The action=y.p isn't necessary, as most User Agents will submit to the same location if no action is specificed
MayorMonty

@Arjun I've tried <form><input required> on the latest Google Chrome version and works as intended. And if you're skeptical, just use action=#. That saves 2 bytes.
Ismael Miguel

3
@Arjun That is a terrible idea for code golfing. I can't say about every browser, since I don't own any Android 1.0, 1.6, 2.0, 2.1, 3.0, 3.1, 4.x.x, 5.x, 6.x, ..., iPhone 2 - 7, every single release of Google Chrome, Firefox 3.0+ and on and on and on and on... In fact, not all HTML5 browsers implement the required attribute! Also, # is a path available since HTML 1.0, if I'm correct. And adding no action to your form is the same as action=".", which is the file itself.
Ismael Miguel

8

Jelly, 3 bytes

ɠṆ¿

Not much to look at on TIO, I'm afraid.

Try it online!

How it works

This is a niladic program, meaning that it takes no input arguments. The implicit argument and return value are both 0 in this case.

¿ (while) is a quick that pops two links from the link stack: a condition () and a body.

is a monadic atom: flat logical NOT. If the previous return value is falsy (here, 0 or an empty string), it returns 1 and the body is called.

ɠ is a niladic atom; it reads a raw line from STDIN and returns the result.

Once ɠ reads a non-empty line, returns 0 and we break out of the loop.


That fast, eh? Ah, well.
Adám



5

Perl 5, 8+1 (-p or -n flag) bytes

/./&&die

Takes input from stdin and dies as soon as the regex matches anything except a newline.


5

C, 52 bytes, 33 bytes, 29 bytes

-19 bytes thanks to Justin

-4 bytes thanks to Christoph

main(){while(getchar()==10);}

10 is equal to '\n' - In case this isn't obvious.


1
You can golf it by 1 char by using a ; instead of the {} for the while loop
Justin

1
Although not standards compliant, you can remove the #include<stdio.h> if you switch to while(getchar()==10): int main(){while(getchar()==10);}.
Justin

2
@Justin main(){while(getchar()==10);} is enough no need for default int.
Christoph

1
main(){scanf("%s");} would also work, if space-only lines can count as empty.
12431234123412341234123

1
@DanielEarwicker You are right. That didn't seem clear to me the first time I read the question, but now I see what you are saying. In that case, there are many non-conforming answers to this question.
Justin

5

Bash, 51 bytes (39 without "#!/bin/bash")

It's my first time participating in PPCG, so dont be to rude ;D

#!/bin/bash
read a
while [ -z "$a" ]
do
read a
done

1
Welcome to PPCG.
Adám

3
Welcome to PPCG!, if you're planning on using Bash as a golfing language you might find This Post Interesting, it has a bunch of tips for making bash programs as small as humanly possible, there's also a More General Version you might want to skim through too.
colsw

@ConnorLSW Wow, thanks, that Post will help me a lot. I'll try to edit my Answer with this new tips ASAP.
Nicolas Fischer

4
you do not need #!/bin/bash
12431234123412341234123

Well, also the first time for me :) But you could perhaps use recursion: [ -z `line` ] && $0 or if the deprecated line is not on your system: [ -z `head -n1` ] && $0. That should either be 20 or 24 bytes.
Yeti

4

Java, 128 126 bytes

2 bytes thanks to Kevin Cruijssen.

import java.util.*;class a{public static void main(String[]a){for(Scanner s=new Scanner(System.in);s.nextLine().isEmpty(););}}

Try it online!


1
You can golf it by two bytes: Change the while to a for and put the Scanner s=new Scanner(System.in); inside it. And change the .equals("") to .isEmpty().
Kevin Cruijssen

I'm pretty sure you can remove the import if you inline the use of the scanner; pretty sure leaking a scanner works just fine: while(new java.util.Scanner(System.in).nextLine().isEmpty());
Justin

4

C# (.NET Core), 66 bytes

class C{static void Main(){for(;System.Console.ReadLine()!="";);}}

Try it online!

-6 bytes thanks to raznagul.


1
You can save 6 bytes by writing System.Console.ReadLIne directly and drop the using-Statement.
raznagul

A while loop would be the same number of bytes, but methinks a more idiomatic way of writing the code than a for loop.
Cody Gray

you can save 24 bytes by writing it as a lambda in the form () => {}
Ceshion

or alternatively, 7 by making it an instance method
Ceshion

4

QBasic 4.5, 15 bytes

INPUT a$:IF a$=""THEN RUN

Asks for input, then checks if any was given. If not, RUN restarts the program.


2
Didn't know about the RUN. +1. (That rhymes too; RUN and PLUS ONE :) )
Arjun

4

Ruby, 13 bytes

gets until/./

I wish gets took a Regexp argument.


4

R, 27 24 23 22 bytes

while(!sum(scan()^0))t

Takes input from stdin, and repeat as long as input is of length 0. Cut off some bytes due to Jarko Dubbeldam and MickyT. Replaced the {} with t to save another byte.


I think you can omit the ,'', since neither input (string or numeric) nor way of terminating was specified in the challenge.
JAD

@JarkoDubbeldam: good catch! I didn't realize errors were a valid termination.
rturnbull

would while(!sum(scan()^0)){} work as well?
MickyT

@MickyT Seems to work. Apparently even Inf^0 is 1. Nice catch with the sum(). Too bad the ^0 is need to handle 0 as input.
JAD

@MickyT That's a great find with the use of sum, thanks! I've updated the answer.
rturnbull

3

PHP, 18 bytes

while(!readline())

Does it check that the line of text is not empty?
Daniel Earwicker

1
Yes, as soon as the line is not empty readline() returns something else than an empty string. Non empty strings evaluate to true in php - atleast most of them do. "0" seems to be an exception as I just read in the docs. Well I guess my answer is wrong now.
Skynet

3

AWK, 8 11 bytes

NF{exit}

Wait for input. If the number of fields in input is more than 0, exit.

EDIT:

I've just realized that this doesn't work for input containing whitespace characters only. IFS needs to be set to empty string using -F "" command line option. Therefore +3 bytes.

Try it online!


Actually, you could replace NF with 1. Then you don't need to set IFS. And grumble you beat me to and AWK solution.
Robert Benson

1
@RobertBenson I tried replacing NF with 1. In that case the program exits given any input, including empty newline.
Maxim Mikhaylov

I missed that part of the spec.
Robert Benson

3

SpecBAS - 34 bytes

1 DO : INPUT a$: LOOP UNTIL a$<>""

Just loops until non-empty string is entered.


3

Mathematica, 26 20 bytes

For[,Input[]==Null,]

1
Shave off six bytes with For[,Input[]==Null,]. Works just as well.
Kelly Lowder

3

Haskell, 19 17 bytes

f=do""<-getLine;f

Defines a function f that if it reads the empty line calls itself again. When reading a non-empty line an exception is raised and the recursion is stopped.

Edit: @Laikoni replaced the parameter with a pattern match and saved 2 bytes. Thanks!


Didn't think Haskell IO code could be as short as this!
Geeky I

17 bytes: f=do""<-getLine;f
Laikoni

@Laikoni: nice catch. Thanks!
nimi

3

Aceto, 9 5 4 bytes

read a value, negate it (!; implicitly casting to a boolean), and mirror horizontally if the value is truthy (|).

!
r|

Wait, Aceto runs **up**‽ And they say APL is strange for running from right to left…
Adám

3
@Adám Aceto runs along a 2D Hilbert curve.
L3viathan

3

Java, 66 64 60 bytes

int a(){return!System.console().readLine().isEmpty()?0:a();}

My first Java answer, would love some tips!


You can probably remove the space between return and !. .equals("") == .isEmpty(). You can return int instead of String. OTOH, return void but either while(System...) or if(System...)a();
Justin

you can do int a(){..?0:a();}, saves 3 bytes
Khaled.K

@Khaled.K actually 4!
OldBunny2800

To @Justin and Khaled.K, thank you for your advice!
OldBunny2800

2

Braingolf, 8 bytes [non-competing]

1[{?:+|]

Non competing because {, which reads input from STDIN, was added to braingolf after this challenge's post date.

Explanation:

1         Pushes 1 to the stack
 [        Begins while loop
  {       Reads from STDIN, returns -1 if no input given
   ?      Checks if last item in stack is > 0
    :     Else
     +    Adds the last 2 items together, however there is only 1 item, so add it to itself
      |   Endif
       ]  End While, decrement first item in stack, or exit if first item is 0

Haha, you implemented input an hour after the challenge was posted
ASCII-only

@ASCII-only had to do it eventually, haha
Skidsdev



2

PowerShell, 20 Bytes

for(;!(read-host)){}

runs a for loop,

read-host prompts for input

if read-host returns nothing it evals to false, so we invert that !(...) and use that as the loop end check.

much shorter than any do{$a=read-host}while($a-eq"") type solution involving variables.



2

CJam, 5 bytes

{l!}g

Try it online! (TIO doesn't really show the proper behaviour)

Explanation

{      e# Do:
 l     e#  Read next line of input
  !    e#  Boolean negate (empty strings are falsy)
   }g  e# Pop the top of stack, if truthy, repeat.
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.