112
\$\begingroup\$

One of the most common standard tasks (especially when showcasing esoteric programming languages) is to implement a "cat program": read all of STDIN and print it to STDOUT. While this is named after the Unix shell utility cat it is of course much less powerful than the real thing, which is normally used to print (and concatenate) several files read from disc.

Task

You should write a full program which reads the contents of the standard input stream and writes them verbatim to the standard output stream. If and only if your language does not support standard input and/or output streams (as understood in most languages), you may instead take these terms to mean their closest equivalent in your language (e.g. JavaScript's prompt and alert). These are the only admissible forms of I/O, as any other interface would largely change the nature of the task and make answers much less comparable.

The output should contain exactly the input and nothing else. The only exception to this rule is constant output of your language's interpreter that cannot be suppressed, such as a greeting, ANSI color codes or indentation. This also applies to trailing newlines. If the input does not contain a trailing newline, the output shouldn't include one either! (The only exception being if your language absolutely always prints a trailing newline after execution.)

Output to the standard error stream is ignored, so long as the standard output stream contains the expected output. In particular, this means your program can terminate with an error upon hitting the end of the stream (EOF), provided that doesn't pollute the standard output stream. If you do this, I encourage you to add an error-free version to your answer as well (for reference).

As this is intended as a challenge within each language and not between languages, there are a few language specific rules:

  • If it is at all possible in your language to distinguish null bytes in the standard input stream from the EOF, your program must support null bytes like any other bytes (that is, they have to be written to the standard output stream as well).
  • If it is at all possible in your language to support an arbitrary infinite input stream (i.e. if you can start printing bytes to the output before you hit EOF in the input), your program has to work correctly in this case. As an example yes | tr -d \\n | ./my_cat should print an infinite stream of ys. It is up to you how often you print and flush the standard output stream, but it must be guaranteed to happen after a finite amount of time, regardless of the stream (this means, in particular, that you cannot wait for a specific character like a linefeed before printing).

Please add a note to your answer about the exact behaviour regarding null-bytes, infinite streams, and extraneous output.

Additional rules

  • This is not about finding the language with the shortest solution for this (there are some where the empty program does the trick) - this is about finding the shortest solution in every language. Therefore, no answer will be marked as accepted.

  • Submissions in most languages will be scored in bytes in an appropriate preexisting encoding, usually (but not necessarily) UTF-8.

    Some languages, like Folders, are a bit tricky to score. If in doubt, please ask on Meta.

  • Feel free to use a language (or language version) even if it's newer than this challenge. Languages specifically written to submit a 0-byte answer to this challenge are fair game but not particularly interesting.

    Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language.

    Also note that languages do have to fulfil our usual criteria for programming languages.

  • If your language of choice is a trivial variant of another (potentially more popular) language which already has an answer (think BASIC or SQL dialects, Unix shells or trivial Brainfuck derivatives like Headsecks or Unary), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language.

  • Unless they have been overruled earlier, all standard rules apply, including the http://meta.codegolf.stackexchange.com/q/1061.

As a side note, please don't downvote boring (but valid) answers in languages where there is not much to golf; these are still useful to this question as it tries to compile a catalogue as complete as possible. However, do primarily upvote answers in languages where the author actually had to put effort into golfing the code.

Catalogue

The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

## Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

## Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

## Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the snippet:

## [><>](http://esolangs.org/wiki/Fish), 121 bytes

<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 62230; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 8478; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "//api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "//api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(42), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>

\$\endgroup\$
14
  • 78
    \$\begingroup\$ Bash, 3 bytes: cat \$\endgroup\$
    – TheDoctor
    Commented Oct 31, 2015 at 19:02
  • 4
    \$\begingroup\$ @TheDoctor I guess this would fall into the "don't use a builtin which does exactly what is needed" rule. \$\endgroup\$ Commented Oct 31, 2015 at 19:46
  • 14
    \$\begingroup\$ @PaŭloEbermann There is no such rule, and the corresponding standard loophole is no longer accepted. (In fact, there is already a sh answer using cat which also contains a shorter solution using dd.) \$\endgroup\$ Commented Oct 31, 2015 at 20:25
  • 1
    \$\begingroup\$ If only it used standard methods of input and output: ///, 0 bytes. \$\endgroup\$
    – sporkl
    Commented Mar 31, 2017 at 19:33
  • 1
    \$\begingroup\$ @SparklePony Except, you'd have to escape slashes and backslashes. \$\endgroup\$ Commented Mar 31, 2017 at 20:35

330 Answers 330

1 2
3
4 5
11
3
\$\begingroup\$

GOTO++, 80 bytes

§1
J=ENTRETONTEXTE()
GOTOPRINT()
GOTONONNULPOURLESNULS %1 entreestd@Fin() - *(1)

Well, GOTO++…As far as I can see, you can either read a line or a number but you can't read a string of a given length. Or just a character for that matter. So this program unfortunately needs linefeeds in its input if it is to ever output anything.

\$\endgroup\$
3
\$\begingroup\$

Perl 5, 11 + 1 (-p flag) = 12 bytes

perl -pe 'INIT{$/=\1}'

Sets the input record separator in an INIT block to work with infinite streams without newlines.

\$\endgroup\$
5
  • \$\begingroup\$ Is this version-dependent? I tried it with Strawberry 5.20.2 and it waited for newlines. \$\endgroup\$
    – msh210
    Commented Nov 2, 2015 at 22:11
  • \$\begingroup\$ @msh210 That's something different. On a terminal, stdin is usually line-buffered, so this behavior is completely normal (just like cat). \$\endgroup\$
    – nwellnhof
    Commented Nov 3, 2015 at 13:59
  • \$\begingroup\$ Very cool! It's a shame you can't set this with -0. Also, -p only adds one byte, not two. \$\endgroup\$ Commented Nov 12, 2015 at 18:41
  • \$\begingroup\$ @ThisSuitIsBlackNot This page says: "This supposes stuff needs no quoting to go in single quotes, or it would need more characters to escape. If not, either the escape characters are counted in as well, or you put the script in a file, and count the difference to perl -nl file.pl, which now includes the hyphen as well as one of the spaces." I removed the single quotes at the expense of a backslash. \$\endgroup\$
    – nwellnhof
    Commented Nov 13, 2015 at 14:23
  • \$\begingroup\$ @nwellnhof That just means that if putting stuff in single quotes requires escaping things, you also have to count the escapes. For example, say"It's alive!" contains a single quote, so you can't put it inside single quotes without escaping. Your answer requires no escaping to go in single quotes, so it scores 11 bytes for the contents of the single quotes, and 1 byte for the -p flag, for 12 total. No need to remove the single quotes, and no need to count them. \$\endgroup\$ Commented Nov 13, 2015 at 15:20
3
\$\begingroup\$

Templates Considered Harmful, 4 bytes

A<1>

This is a language which is executed by having the C++ compiler figure out the type of a typedef in a template. The language only supports finite input.

A<1> refers to the first argument of an anonymous function. All user-defined functions are anonymous. A program is implicitly wrapped in Fun<>, so it defines a function that returns its first argument, which is the input.

\$\endgroup\$
3
\$\begingroup\$

Mathematica, 43 bytes

While[a=!=EndOfFile,Print[a=InputString[]]]
\$\endgroup\$
1
  • 2
    \$\begingroup\$ Uhh, I think you meant While[Echo[InputString[]]=!=EndOfFile] which has the same byte count, but can be shortened to While[Echo@InputString[]=!=EndOfFile] \$\endgroup\$ Commented Nov 13, 2015 at 16:03
3
\$\begingroup\$

Gaot++, 171 bytes

bleeeeeeeeeeeet
bleeeet bleeeeeet
bleeeeeeeeeet bleeeet blet
bleeeeeeeeeeeet bleeeet blet
bleeeeeeeeeeeeet bleeeet blet
bleeeeeeeeeeeeet bleeeet blet
bleeeeeeeet bleeeeeet

Compressed: 12e 4e 6e 10e 4e 1e 12e 4e 1e 13e 4e 1e 13e 4e 1e 8e 6e

Try it online!

Explanation

X 4e 1e, where 1e (blet) is a nop, basically forms a pattern where if you go from left to right, X is executed, but not from right to left.

Alternatively, if you have X 4e Y, then X is executed when you go from left to right, and Y otherwise.

\$\endgroup\$
1
  • \$\begingroup\$ Just a suggestion: use b instead of blet. Use b instead of 1e. I have tested it, and it works. \$\endgroup\$ Commented Oct 30, 2016 at 9:17
3
\$\begingroup\$

Addict, 31 bytes

Addict is my new Turing-tarpit esolang, based on PRINDEAL. Addict has 5 commands: alias, decrement, increment, char, and take. See the GitHub repo for more details.

a I
 t c
 O
 d
a O
 c c
 I
 d
I

Test it online here!

This basically defines a loop which repeatedly inputs a charcode and outputs it, until EOF is reached. Ungolfed version:

a input  # Define a command `input` that does the following:
 t char  #   Set variable `char` to the next charcode in the input.
 output  #   If there is a next charcode, run command `output`.
 d       #   Otherwise, just exit.

a output # Define a command `output` that does the following:
 c char  #   Output variable `char` as a charcode.
 input   #   Attempt to input again.
 d       #   (This line never gets run.)

input  # Run command `input`.
\$\endgroup\$
3
\$\begingroup\$

R, 14 bytes

Output stdin, nothing fancy.

cat(scan(,''))

If stdin consists solely of numbers, you can do it in 11 bytes with cat(scan()).

As far as I know, there's no way to handle infinite input.

\$\endgroup\$
1
3
\$\begingroup\$

Javascript, 25 23 22 bytes

for(;;)alert(prompt())

Edit: Thanks to stefnotch for saving 2 3 bytes

\$\endgroup\$
2
  • \$\begingroup\$ You could golf it like this: for(;;alert(prompt())); Here is a link that might help: codegolf.stackexchange.com/questions/2682/… \$\endgroup\$
    – Stefnotch
    Commented Oct 30, 2015 at 19:17
  • \$\begingroup\$ Just realized that you could have the function outside the loop, saving yet another byte for(;;)alert(prompt()) \$\endgroup\$
    – Stefnotch
    Commented Feb 12, 2017 at 18:08
3
\$\begingroup\$

Whitespace, 29 26 bytes


  
   
 
 	
	 				
  
 


Try it online!

Continuously reads a character from STDIN and outputs it to STDOUT. Unprintable characters including NUL bytes are handled like any other character, only EOF will terminate the program.

Explanation

(s - space, t - tab, n - newline)

nssn # Label ''
sssn # Push 0 - stack: [0]
sns  # Duplicate the top item on the stack - stack: [0, 0]
tnts # Pop, read a character from STDIN and place it at the address given by the popped value - stack: [0] heap: [0:<char>]
ttt  # Pop, push the heap value at the address given by the popped value - stack: [<char>]
tnss # Pop, output the popped value as a character to STDOUT - stack: []
nsnn # Jump to label ''
\$\endgroup\$
3
\$\begingroup\$

Brain-Flak, 0 + 3 = 3 bytes

Needs the -c flag.


Try it online!

This language cannot possibly handle infinite input streams.

This language absolutely always appends a trailing newline to the output.

In the original Ruby interpreter, the input is a command-line arg instead of a STDIN stream. The online interpreter seems to have been modified.

\$\endgroup\$
3
\$\begingroup\$

05AB1E, 4 2 bytes (not working)

Try it online!

Golfed from 4 to 2 bytes thanks to @daHugLenny!

Explanation

|       Takes input as array separated by breaks
 »      Join input array by newline
        Implicitly print
\$\endgroup\$
8
3
\$\begingroup\$

Shakespeare Programming Language, 96 bytes

,.Ajax,.Page,.Act I:.Scene I:.[Exeunt][Enter Page and Ajax]Ajax:Open mind!Speak thy!Let usAct I!

Try it online!

Some nice and weird grammer. Terminates in an error.

Shakespeare Programming Language, 125 bytes

,.Ajax,.Page,.Act I:.Scene I:.[Exeunt][Enter Page and Ajax]Ajax:Open mind!Be you nicer a pig?If sospeak thy!If solet usAct I!

Try it online!

Non-erroring version. I especially liked constructing the sentence If solet usact I!

\$\endgroup\$
3
\$\begingroup\$

Grocery List, 14 bytes

*but it doesn't look like a grocery list

h

i
l
p
i
e
t

Explanation:

Title

i nput
l oop
p op and print
i nput
e nd loop if nonzero
t erminate
\$\endgroup\$
3
\$\begingroup\$

Keg, 0 8 bytes

{?(,)\
,

Supports multi-line input now. Halts in an error, which is allowed by default

Try it Online!

\$\endgroup\$
1
  • \$\begingroup\$ fixed (padding) \$\endgroup\$
    – EdgyNerd
    Commented Aug 24, 2019 at 14:26
3
\$\begingroup\$

Gol><>, 2 bytes

credit to Jo King

io

Try it online!

Errors out on EOF. The error message goes to stderr.

How it works

io

i   Push an input char
 o  Pop and print; error if last input hit EOF
    Repeat indefinitely

Gol><>, 4 bytes

iE;o

Try it online!

No-error version.

How it works

iE;o

i     Push an input char
 E;   Halt on EOF
   o  Pop and print
      Repeat indefinitely
\$\endgroup\$
0
3
\$\begingroup\$

C, 17, 16 bytes

main(){tee(0,1);}

This only works on certain compilers (such as tutorialspoint which uses GCC), but it's really short.

main(){tee(1j);}

Edit: Now down to 16 bytes! j is a GNU suffix which acts as a complex
number. Basically tee(1j) == tee(0,1). This trick also only works in rare cases.

\$\endgroup\$
3
\$\begingroup\$

MAWP, 7 bytes

|0~[;].

Try it!

Explanation:

|      Push input to stack
0      Add a zero to stack
~      Reverse stack
[;]    Output each character from stack until 0
.      Terminate program
\$\endgroup\$
3
\$\begingroup\$

vJASS (Warcraft 3), 202 181 bytes

Using //! import zinc "<code_path>" command to exclude //! zinc and //! endzinc.


library a{trigger t=CreateTrigger();function onInit(){TriggerRegisterPlayerChatEvent(t,Player(0),"",false);TriggerAddAction(t,function(){BJDebugMsg(GetEventPlayerChatString());});}}

Readable Version:

library a{
   trigger t = CreateTrigger();

   function onInit(){
      // Create an INPUT EVENT
      TriggerRegisterPlayerChatEvent(t, Player(0), "", false);
      TriggerAddAction(t, function(){BJDebugMsg(GetEventPlayerChatString());});
   }
}
\$\endgroup\$
3
+100
\$\begingroup\$

, 5 bytes

No interpreter yet, but:

#@$,*

When unfolded into a cube, it adds a no-op:

  #
@ $ , *
  .

The IP starts in the top cell (#) and "falls" downwards, into the $. I'll try to explain the code the best I can (which is not very well):

#   Later acts as "ground," not letting the IP pass through it. However, the IP checks for ground AFTER running commands, so '#' does nothing here.
    (The IP falls downwards after running each command.)
$   Ignores the next command if the current memory cell is 0. The memory cells all start at 0, and since the memory has not been changed at all, it ignores the next command.
.   No-op, does not count as command.
    (If the IP goes out of the area, it goes to a corresponding cell and rotates its direction and , as if the code were written on the faces of a cube.)
*   Prints the output from the current memory cell. However, this is not run, because '$' ignored this command.
    (If the IP falls or moves into '#', it snaps back to its previous position and moves in its given direction. It starts facing right, however after leaving the cube's map, it now faces left, so the IP now moves left and continues to do this for the rest of the program's runtime.)

,   ("Actual" start of program) Inputs next ASCII character in input to the current memory cell.
$   Ignores next command if the end has been reached (EOF returns 0).
@   Terminates the program if the end has been reached.
*   Output ASCII character from the current memory cell.

(Program continues from last ',')

I don't think it's possible to golf it into 4 bytes, but I hope I'm wrong.

\$\endgroup\$
7
  • \$\begingroup\$ Looks like an interesting language! Did you make it? \$\endgroup\$ Commented Jan 22, 2021 at 21:38
  • 1
    \$\begingroup\$ @RedwolfPrograms Yep :) It's basically a mix between MarioLANG and Cubix. \$\endgroup\$
    – Bo_Tie
    Commented Jan 23, 2021 at 22:26
  • \$\begingroup\$ If you write an interpreter make sure to let me know, as this (or another) answer will be able to receive a bounty! \$\endgroup\$ Commented Jan 23, 2021 at 22:45
  • \$\begingroup\$ @RedwolfPrograms Made an interpreter! repl.it/@BoTie/v3-Interpreter#script.txt \$\endgroup\$
    – Bo_Tie
    Commented Feb 3, 2021 at 18:20
  • \$\begingroup\$ Looks really cool! Definitely deserves the bounty. Let me know if you want it on this answer, or if you think a different one would show off more of the features! \$\endgroup\$ Commented Feb 3, 2021 at 18:25
3
\$\begingroup\$

Arduino, 45 27 + ? bytes

This is a pretty standard diagnostic test for Arduino serial ports, just golfed down a little.

void setup(){}void loop(){}

After testing, it turns out the Serial.begin(300); is totally unnecessary, making this code the same as the shortest infinite loop.

The ? is because this requires a physical wire connecting pin 0 to pin 1, and I have no clue how to count that. For completeness' sake, here's a version that doesn't require that, which is 95 91 bytes:

#define S Serial
void setup(){S.begin(300);}void loop(){S.available()&&S.write(S.read());}

Or, cleaned up a little:

#define S Serial

void setup() {
  S.begin(300);
}

void loop() {
  S.available() &&
    S.write(S.read());
}

The S.available() check is necessary because Serial.read() returns -1, not 0, when there are no bytes available to read.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ You don't generally have to count hardware stuff, which is a rule that mostly makes sense but breaks down for this sort of thing. The reasoning is that different hardware is a different language. For example 45 bytes of clojure code that only works on intel processors is not better than 46 bytes of clojure that works on any processor, just like 6 bytes in Jelly is not better than 304 bytes of Java. They are different. So as weird as it sounds this is a 45 byte answer in the language "Arduino, with a wire connecting pin 0 to pin 1". \$\endgroup\$
    – Wheat Wizard
    Commented Aug 13, 2021 at 6:57
  • 1
    \$\begingroup\$ It kind of sucks that there is no official way to count this, but that's just kind of how it is. Hardware stuff is just not super well supported. Welcome to the site anyway! \$\endgroup\$
    – Wheat Wizard
    Commented Aug 13, 2021 at 6:59
3
\$\begingroup\$

Plumber, 16 bytes

[]=[[]
 [[[[=
][][

First answer in my new esolang!

Programs in plumber are divided into 2 character wide units, each of which performs a certain function. All [] units on the top row will drop a packet containing the value 0. The one on the right will hit the [=, which will pop input and push it left into a right-facing branch dropper ([[). Branch droppers push in the direction they are facing, and also drop the value. When the value is pushed into the [=, it is outputted.

Plumber uses -1 for EOF, and outputting a negative value does nothing. When the value drops into the ][][, it moves upward on the far left, passes through an increment ( [) operator, and is picked up by the []. If it is not 0, is passes through the conditional (=[), and is dropped by the [] on the right. This continues until the input is -1.

\$\endgroup\$
3
\$\begingroup\$

Spice, 14 bytes

;n@REA n;OUT n

Explanation:

;n@     Declare 'n'
REA n;  Read input into 'n'
OUT n   Output value of 'n'
\$\endgroup\$
2
\$\begingroup\$

C--, 171 bytes

target byteorder little;import getchar,putchar;export main;foreign"C"main(){t:bits32 v;v=foreign "C" getchar();if(v!=-1){foreign"C"putchar(v);goto t;}foreign"C"return(0);}

Considering C-- is essentially a "portable assembler", I shouldn't be surprised that this was huge.

\$\endgroup\$
2
\$\begingroup\$

Befunge-98, 4 bytes

#@~,

The program counter starts moving to the right in the top-left corner of the program. # causes it to jump over @, landing on ~. This reads a character, or reflects the PC on EOF. If EOF is reached, this will cause it to run into @, which ends the program. Otherwise, it continues to ,, which prints the character that was read, and loops back to # thanks to Lahey-space.

\$\endgroup\$
3
  • \$\begingroup\$ Is the reflect-on-EOF behavior in the spec? I didn't know about it before. (Then again, I coded mostly in Befunge-93.) \$\endgroup\$ Commented Oct 30, 2015 at 16:52
  • \$\begingroup\$ Yeah: In the case of an end-of-file or other file error condition, the & and ~ both act like r. \$\endgroup\$
    – lynn
    Commented Oct 30, 2015 at 16:53
  • \$\begingroup\$ Huh, interesting. The lack of this behavior in Befunge-93 added five bytes! Doubled the program length! \$\endgroup\$ Commented Oct 30, 2015 at 16:54
2
\$\begingroup\$

Python 3, 50 bytes

import sys
while 1:print(sys.stdin.read(1),end='')

See comment in my python 2 answer about newlines.

OR 29 bytes

while 1:print(input())

Waits explicitly for newlines before printing. (This means that it won't print anything after a newline before the next)

\$\endgroup\$
6
  • 1
    \$\begingroup\$ Adds trailing newline. \$\endgroup\$
    – feersum
    Commented Oct 30, 2015 at 16:42
  • \$\begingroup\$ Can't you do print(end=sys.stdin.read(1))? \$\endgroup\$ Commented Sep 27, 2016 at 17:52
  • \$\begingroup\$ I've found a shorter one using os.read/write and fd numbers, it is 42 bytes. tio.run/##K6gsycjPM/7/… \$\endgroup\$ Commented Dec 28, 2018 at 18:23
  • \$\begingroup\$ Feel free to post it yourself and take the credit for it^^ \$\endgroup\$
    – Blue
    Commented Dec 28, 2018 at 18:32
  • \$\begingroup\$ Does input always have to be read? If not you could cut off 8 bytes to print(input()) \$\endgroup\$ Commented Aug 1, 2022 at 13:44
2
\$\begingroup\$

Pyth, 28 bytes

V$__import__('sys').stdin$pN

Not as short as @Mauris's Pyth answer, but it handles infinite input.

\$\endgroup\$
2
\$\begingroup\$

Erlang, 108 Bytes

Uses escript to run. Making the code a one-liner seems to cause an EOF error from the interpreter.

#!/usr/bin/env escript
main(_)->f(a).
f(eof)->ok;f([C])->f(io:format("~c",[C]));f(_)->f(io:get_chars('',1)).
\$\endgroup\$
2
\$\begingroup\$

lua for windows, 38 bytes

Needs lua for windows

while true do io.write(io.read()) end

how it works

It prints the input from the terminal

\$\endgroup\$
1
  • \$\begingroup\$ You can make it shorter using a true condition _G (the global table) and removing the space after the last brace. \$\endgroup\$ Commented Jan 23, 2021 at 2:25
2
\$\begingroup\$

Julia, 45 bytes

while !eof(STDIN) print(read(STDIN,Char))end

Ungolfed + explanation:

while !eof(STDIN)             # While EOF has not been encountered from STDIN
    r = read(STDIN, Char)     # Read a single character from STDIN
    print(r)                  # Print it to STDOUT with no trailing anything
end

This supports an infinite input stream and null bytes and has no extraneous output.

Thanks to Dennis and Martin Büttner for their help on this!

\$\endgroup\$
0
2
\$\begingroup\$

QBasic, 15 bytes

?INPUT$(1);
RUN

QBasic doesn't have any concept of input or output streams (except maybe where files are concerned). The above program instead takes any character you enter and echoes it to the screen, which I think fits the spirit of the challenge. RUN restarts the program from scratch, thus continuing to read and echo forever (there's no EOF for keyboard input, and I don't think it's even possible to enter a null byte).

Here's a 34-byte version that quits when you press escape. The should be replaced with a literal Esc character, ASCII 27. This can be entered in the QBasic editor by holding the Alt key while typing the character code; it shows up as a .

9?x$;
x$=INPUT$(1)
IF"…"<>x$THEN 9
\$\endgroup\$
1 2
3
4 5
11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.