Domagaj się odpowiedzi


31

W czasie wykonywania monituj o wiersz danych wejściowych, dopóki użytkownik nie wprowadzi czegoś (innego niż pusta nowa linia), tj. Nie tylko naciska Enterani OK. Wynik lub wynik nie jest wymagany ani zabroniony.

Pseudokod 1

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

Pseudokod 2

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

Przykład 1

Program działa i natychmiast wyskakuje formularz z pojedynczym polem tekstowym i OKprzyciskiem.
Użytkownik klika OKprzycisk.
Nic się nie dzieje.
Użytkownik wkleja „hello world” w pole tekstowe i klika przyciskOK przycisk.
Program kończy się.

Przykład 2

Funkcja jest wywoływana i natychmiast wyświetla pustą linię i migający kursor.
Użytkownik naciska Enter.
Kursor przesuwa się o jedną linię w dół.
Użytkownik naciska Enter.
Kursor przesuwa się o jedną linię w dół.
Użytkownik naciska PPCGEnter
Funkcja zwraca.


czy wolno liczyć wiersze zawierające tylko spację jako puste?
12431234123412341234123

@ 12431234123412341234123 Nie.
Adám

Czy trzeba poczekać na pełną linię, gdy użytkownik zacznie wprowadzać dane?
Matteo Italia

Ok, z komentarza w usuniętej odpowiedzi @ CodyGray wygląda na to, że jest niedozwolona.
Matteo Italia,

@MatteoItalia Tak, poprawne; wiersz wprowadzania .
Adám

Odpowiedzi:


16

TI-BASIC, 2 bajty

:Prompt X

TI-BASIC robi to automatycznie. Po podaniu danych zostanie zakończone.

Oto GIF:

enter image description here

Obserwuj liczbę enternaciśnięć klawisza w historii naciśnięć klawiszy. Utworzono za pomocą TI-SmartView CE i ezgif.com .


1
Hmm .. to są 2 bajty?
Naukowy I

9
TI-BASIC jest oparty na tokenach .
Scott Milner

A odpowiedź nie zajmie Enter? Czy jest gdziekolwiek przetestować to online?
Adám

@ Adám Nie trzeba wchodzić, aby uzyskać odpowiedź. O ile mi wiadomo, nie ma miejsca, do którego można przejść online bez posiadania obrazu TI ROM. Ale mogę wysłać .gif, kiedy wrócę do domu.
Scott Milner,

1
@ Adám Testowanie TI-BASIC online bez posiadania ROM jest nielegalne.
Erik the Outgolfer


15

sed, 4

/./q

Czeka na linię wejściową zawierającą 1 lub więcej znaków, a następnie kończy działanie.

Wypróbuj online . Ale działa lepiej w przypadku powłoki na żywo:

sed '/./q'

15

JavaScript, 37 22 17 bajtów

while(!prompt());

while(!prompt());

Wyjaśnienie

Słowo whilekluczowe uruchamia whilepętlę. W stanie pętli !prompt()pyta o dane wejściowe i sprawdza, czy są one podane, czy nie. Jeśli nie zostanie podany, ciało pętli zostanie wykonane, które w naszym przypadku jest puste, wówczas interpreter wraca do stanu pętli. Ten sam proces odbywa się w kółko, dopóki użytkownik nie poda danych wejściowych.


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

@ Adám Wow. Właśnie myślałem o tym, jak zmniejszyć rozwiązanie, a ty znalazłeś odpowiedź dzięki!
Arjun

To wydawało się oczywiste. Jednak moja konsola przeglądarki odmawia wykonania bez zakończenia ;, a początkowe wyrażenie działało bez ;. Masz pomysł, dlaczego?
Adám

Nie, Chrome. Jeśli więc jakikolwiek silnik JavaScript poradzi sobie z pominięciem bieżącego wyrażenia ;, możesz zapisać ten bajt :-)
Adám

1
@ Adám Właśnie odkryłem prawdziwą przyczynę błędu powstającego po usunięciu średnika z kodu źródłowego. Powodem tego jest to, że pętla while oczekuje instrukcji (lub grupy instrukcji) jako treści pętli po warunku pętli. Dodanie średnika sprawia, że ​​wydaje się, że ciało pętli się skończyło. Jednak usunięcie średnika powoduje oczekiwanie następnej instrukcji jako treści pętli. Ale w naszym przypadku po warstwie pętli nie pojawiają się nowe instrukcje. Zgłasza więc błąd. Mam nadzieję, że teraz jest jasne. Jestem okropny w wyjaśnianiu rzeczy !! : p
Arjun

9

Java, 55 bajtów

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

Jeśli dobrze pamiętam (minęło trochę czasu, odkąd jestem aktywny na PPCG), mój program może być tylko funkcją.

Jest to specyficzne dla systemu; działa tylko w systemach, w których znak końca wiersza jest pojedynczą nową linią. Jeśli znak end-of-line jest raczej powrót karetki, wymienić 10się 13. W systemie Windows to nie działa, ponieważ w systemie Windows jest to koniec linii \r\n.

Wykorzystuje to fakt, że mogę czytać bezpośrednio z System.in.


2
Witamy ponownie, choćby po tę odpowiedź! : D
Conor O'Brien

3
Witamy ponownie @ Justin!
Cyfrowa trauma

1
Nie planuję być aktywny; po prostu wpadam na pytanie tu i tam
Justin

Aby uniknąć problemu „nie działa w systemie Windows”, nie możesz po prostu przetestować pierwszego znaku i sprawdzić, czy tak jest \r, w przeciwieństwie do testowania całego łańcucha, a następnie napotkania problemów z występowaniem 2 znaków EOL?
Cody Gray

@CodyGray Nie. Czytam 1 znak na raz; to wszystko, System.inco możesz zrobić bezpośrednio (cóż, możesz jednocześnie czytać tablicę znaków). Moje ciało pętli (puste) jest uruchamiane dla każdego znaku na wejściu
Justin

9

HTML5, 33 22 bajtów

<form><input required>

<form><input required>

Wyjaśnienie

requiredAtrybut na<input> powoduje, że przeglądarka informuje użytkownika „To pole jest wymagane” -sort depeszy, jeżeli nie wprowadzić wartość. Jednak po wprowadzeniu wartości wartość jest wysyłana na adres URL actionatrybutu <form>(którym w naszym przypadku jest sam plik bieżący, ponieważ nie podaliśmy żadnej wartości jawnie).

Zostało to przetestowane na najnowszej wersji Google Chrome (wersja 55.0). Może działać w innych przeglądarkach i wersjach.


action=/może działać w niektórych przeglądarkach.
Neil

1
Prawdopodobnie możesz actioncałkowicie rzucić atrybut.
Kudłaty

1
@Arjun Nie action=y.pjest to konieczne, ponieważ większość agentów użytkownika prześle się do tej samej lokalizacji, jeśli nie actionokreślono
inaczej

@Arjun Próbowałem <form><input required>na najnowszej wersji Google Chrome i działa zgodnie z przeznaczeniem. A jeśli jesteś sceptyczny, po prostu użyj action=#. To oszczędza 2 bajty.
Ismael Miguel

3
@Arjun To okropny pomysł na golfa kodu. Nie mogę powiedzieć o każdej przeglądarce, ponieważ nie posiadam żadnego Androida 1.0, 1.6, 2.0, 2.1, 3.0, 3.1, 4.xx, 5.x, 6.x, ..., iPhone 2 - 7, każda wersja Google Chrome, Firefox 3.0+ i dalej i dalej i dalej i dalej ... W rzeczywistości nie wszystkie przeglądarki HTML5 implementują ten requiredatrybut! Ponadto, #jest to ścieżka dostępny od HTML 1.0, jeśli się nie mylę. Dodanie „nie” actiondo formularza jest tym samym action=".", co sam plik.
Ismael Miguel

8

Galaretka , 3 bajty

ɠṆ¿

Obawiam się, że nie ma wiele do obejrzenia na TIO.

Wypróbuj online!

Jak to działa

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

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

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.
Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.