Input/Output for lines of text: Difference between revisions
(Applesoft BASIC) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 34: | Line 34: | ||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="11l">F do_stuff(words) |
||
print(words) |
print(words) |
||
Line 40: | Line 40: | ||
L 1..linecount |
L 1..linecount |
||
V line = input() |
V line = input() |
||
do_stuff(line)</ |
do_stuff(line)</syntaxhighlight> |
||
=={{header|Action!}}== |
=={{header|Action!}}== |
||
The user must type in the monitor the following command after compilation and before running the program!<pre>SET EndProg=*</pre> |
The user must type in the monitor the following command after compilation and before running the program!<pre>SET EndProg=*</pre> |
||
{{libheader|Action! Tool Kit}} |
{{libheader|Action! Tool Kit}} |
||
< |
<syntaxhighlight lang="action!">CARD EndProg ;required for ALLOCATE.ACT |
||
INCLUDE "D2:ALLOCATE.ACT" ;from the Action! Tool Kit. You must type 'SET EndProg=*' from the monitor after compiling, but before running this program! |
INCLUDE "D2:ALLOCATE.ACT" ;from the Action! Tool Kit. You must type 'SET EndProg=*' from the monitor after compiling, but before running this program! |
||
Line 83: | Line 83: | ||
OD |
OD |
||
nLines=0 |
nLines=0 |
||
RETURN</ |
RETURN</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Input_Output_for_lines_of_text.png Screenshot from Atari 8-bit computer] |
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Input_Output_for_lines_of_text.png Screenshot from Atari 8-bit computer] |
||
Line 98: | Line 98: | ||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
<syntaxhighlight lang="ada">-- |
|||
<lang Ada>-- |
|||
-- The first line contains the number of lines to follow, followed by that |
-- The first line contains the number of lines to follow, followed by that |
||
-- number of lines of text on STDIN. |
-- number of lines of text on STDIN. |
||
Line 118: | Line 118: | ||
end loop; |
end loop; |
||
end Main; |
end Main; |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''Input:''' |
'''Input:''' |
||
<pre> |
<pre> |
||
Line 135: | Line 135: | ||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}} |
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}} |
||
< |
<syntaxhighlight lang="algol68"># outputs line plus a newline # |
||
PROC show line = ( STRING line )VOID: |
PROC show line = ( STRING line )VOID: |
||
print( ( line, newline ) ); |
print( ( line, newline ) ); |
||
Line 146: | Line 146: | ||
show line( ( STRING line; read( ( line, newline ) ); line ) ) |
show line( ( STRING line; read( ( line, newline ) ); line ) ) |
||
OD |
OD |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|ALGOL W}}== |
=={{header|ALGOL W}}== |
||
< |
<syntaxhighlight lang="algolw">begin |
||
% outputs line on a newline % |
% outputs line on a newline % |
||
procedure showLine ( string(80) value line ); write( line ); |
procedure showLine ( string(80) value line ); write( line ); |
||
Line 160: | Line 160: | ||
showLine( line ) |
showLine( line ) |
||
end for_lineNumber |
end for_lineNumber |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|Applesoft BASIC}}== |
=={{header|Applesoft BASIC}}== |
||
< |
<syntaxhighlight lang="gwbasic"> 100 GOSUB 230"INPUT LINE" |
||
110 LET N = VAL (L$) - 1 |
110 LET N = VAL (L$) - 1 |
||
120 IF N < 0 THEN END |
120 IF N < 0 THEN END |
||
Line 184: | Line 184: | ||
300 NEXT C |
300 NEXT C |
||
310 LET C = FRE (0) |
310 LET C = FRE (0) |
||
320 RETURN</ |
320 RETURN</syntaxhighlight> |
||
'''Input''' |
'''Input''' |
||
<pre> |
<pre> |
||
Line 199: | Line 199: | ||
</pre> |
</pre> |
||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
<syntaxhighlight lang="awk"> |
|||
<lang AWK> |
|||
# syntax: GAWK -f INPUT_OUTPUT_FOR_LINES_OF_TEXT.AWK |
# syntax: GAWK -f INPUT_OUTPUT_FOR_LINES_OF_TEXT.AWK |
||
BEGIN { |
BEGIN { |
||
Line 210: | Line 210: | ||
exit(0) |
exit(0) |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Batch File}}== |
=={{header|Batch File}}== |
||
< |
<syntaxhighlight lang="dos"> |
||
@echo off |
@echo off |
||
setlocal enabledelayedexpansion |
setlocal enabledelayedexpansion |
||
Line 223: | Line 223: | ||
for /l %%i in (1,1,%lines%) do echo !line%%i! |
for /l %%i in (1,1,%lines%) do echo !line%%i! |
||
pause>nul |
pause>nul |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{in}} |
{{in}} |
||
<pre> |
<pre> |
||
Line 239: | Line 239: | ||
=={{header|C}}== |
=={{header|C}}== |
||
<syntaxhighlight lang="c"> |
|||
<lang C> |
|||
#include<stdlib.h> |
#include<stdlib.h> |
||
#include<stdio.h> |
#include<stdio.h> |
||
Line 270: | Line 270: | ||
return 0; |
return 0; |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
Alternative code: |
Alternative code: |
||
Line 282: | Line 282: | ||
When the total number of lines entered has been reached, it will display a message indicating that you must enter a number. |
When the total number of lines entered has been reached, it will display a message indicating that you must enter a number. |
||
<syntaxhighlight lang="c"> |
|||
<lang C> |
|||
// Programa IO.C |
// Programa IO.C |
||
#include <stdio.h> |
#include <stdio.h> |
||
Line 332: | Line 332: | ||
return 0; |
return 0; |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 352: | Line 352: | ||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang="cpp">#include <iostream> |
||
#include <vector> |
#include <vector> |
||
Line 374: | Line 374: | ||
std::cout << value << "\n"; |
std::cout << value << "\n"; |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
'''Input:''' |
'''Input:''' |
||
<pre> |
<pre> |
||
Line 390: | Line 390: | ||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang="d">void main() { |
||
import std.stdio, std.conv, std.string; |
import std.stdio, std.conv, std.string; |
||
Line 397: | Line 397: | ||
foreach (_; 0 .. readln.strip.to!uint) |
foreach (_; 0 .. readln.strip.to!uint) |
||
doStuff(readln.idup); |
doStuff(readln.idup); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
{{libheader| System.SysUtils}} |
{{libheader| System.SysUtils}} |
||
<syntaxhighlight lang="delphi"> |
|||
<lang Delphi> |
|||
program Output_for_Lines_of_Text; |
program Output_for_Lines_of_Text; |
||
Line 448: | Line 448: | ||
Writeln(lines); |
Writeln(lines); |
||
Readln; |
Readln; |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 462: | Line 462: | ||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
< |
<syntaxhighlight lang="factor">USING: io kernel strings ; |
||
IN: input-output |
IN: input-output |
||
Line 468: | Line 468: | ||
M: string do-stuff print ; |
M: string do-stuff print ; |
||
readln drop [ do-stuff ] each-line</ |
readln drop [ do-stuff ] each-line</syntaxhighlight> |
||
=={{header|Free Pascal}}== |
=={{header|Free Pascal}}== |
||
This requires FPC – the FreePascal compiler – to be in a configuration enabling the use ob <tt>object</tt>s. |
This requires FPC – the FreePascal compiler – to be in a configuration enabling the use ob <tt>object</tt>s. |
||
< |
<syntaxhighlight lang="pascal">program head(input, output, stdErr); |
||
type |
type |
||
Line 496: | Line 496: | ||
obj.method(line); |
obj.method(line); |
||
end; |
end; |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
||
Sub printLines(lines() As String) |
Sub printLines(lines() As String) |
||
Line 515: | Line 515: | ||
Print |
Print |
||
printLines lines() |
printLines lines() |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 530: | Line 530: | ||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 581: | Line 581: | ||
func doStuff(line string) { |
func doStuff(line string) { |
||
fmt.Println(line) |
fmt.Println(line) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
< |
<syntaxhighlight lang="haskell">import Control.Monad |
||
main = do |
main = do |
||
number <- getLine |
number <- getLine |
||
input <- replicateM (read number) getLine |
input <- replicateM (read number) getLine |
||
mapM_ putStrLn input |
mapM_ putStrLn input |
||
</ |
</syntaxhighlight>'''Input:''' |
||
<pre> |
<pre> |
||
3 |
3 |
||
Line 607: | Line 607: | ||
Example in bash. jconsole is on the PATH. |
Example in bash. jconsole is on the PATH. |
||
<syntaxhighlight lang="j"> |
|||
<lang J> |
|||
$ cat <<EOF | jconsole -js '2!:55@:0:@:(; (1!:2) 4:)@:(}. {.~ _ ". [: }: 0&{::)@:(<;.2)@:(1!:1) 3' |
$ cat <<EOF | jconsole -js '2!:55@:0:@:(; (1!:2) 4:)@:(}. {.~ _ ". [: }: 0&{::)@:(<;.2)@:(1!:1) 3' |
||
> 3 |
> 3 |
||
Line 617: | Line 617: | ||
hello world |
hello world |
||
Pack my Box with 5 dozen liquor jugs |
Pack my Box with 5 dozen liquor jugs |
||
</syntaxhighlight> |
|||
</lang> |
|||
From the dictionary of j (DOJ) the data flow for the fork (f g h) is |
From the dictionary of j (DOJ) the data flow for the fork (f g h) is |
||
Line 669: | Line 669: | ||
=={{header|Java}}== |
=={{header|Java}}== |
||
< |
<syntaxhighlight lang="java">import java.util.Scanner; |
||
public class Main { |
public class Main { |
||
Line 684: | Line 684: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
{{works with|Julia|0.6}} |
{{works with|Julia|0.6}} |
||
< |
<syntaxhighlight lang="julia">function dosomething(words) |
||
print(words) |
print(words) |
||
end |
end |
||
Line 697: | Line 697: | ||
words = readline() |
words = readline() |
||
dosomething(words) |
dosomething(words) |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<syntaxhighlight lang="scala">// version 1.1 |
||
fun output(lines: Array<String>) = println(lines.joinToString("\n")) |
fun output(lines: Array<String>) = println(lines.joinToString("\n")) |
||
Line 710: | Line 710: | ||
println("\nThe lines you entered are:\n") |
println("\nThe lines you entered are:\n") |
||
output(lines) |
output(lines) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 729: | Line 729: | ||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
< |
<syntaxhighlight lang="lua">function show (t) |
||
for _, line in pairs(t) do print(line) end |
for _, line in pairs(t) do print(line) end |
||
end |
end |
||
Line 735: | Line 735: | ||
local lineTable, numLines = {}, io.read() |
local lineTable, numLines = {}, io.read() |
||
for i = 1, numLines do table.insert(lineTable, io.read()) end |
for i = 1, numLines do table.insert(lineTable, io.read()) end |
||
show(lineTable)</ |
show(lineTable)</syntaxhighlight> |
||
=={{header|Nanoquery}}== |
=={{header|Nanoquery}}== |
||
{{trans|Ursa}} |
{{trans|Ursa}} |
||
< |
<syntaxhighlight lang="nanoquery">// get how many lines the user wants |
||
amount = int(input()) |
amount = int(input()) |
||
Line 752: | Line 752: | ||
for line in lines |
for line in lines |
||
println line |
println line |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>3 |
<pre>3 |
||
Line 764: | Line 764: | ||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang="nim">import strutils |
||
proc write(line: string) = |
proc write(line: string) = |
||
Line 772: | Line 772: | ||
for _ in 1..lineCount: |
for _ in 1..lineCount: |
||
let line = stdin.readLine() |
let line = stdin.readLine() |
||
line.write()</ |
line.write()</syntaxhighlight> |
||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang="objeck">use System.IO.File; |
||
class Rosetta { |
class Rosetta { |
||
Line 794: | Line 794: | ||
}; |
}; |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
This task is not possible to implement directly in GP: for <code>input()</code> to take a string the user would have to wrap it in quotes (and escape quotes and newlines). One must use PARI: |
This task is not possible to implement directly in GP: for <code>input()</code> to take a string the user would have to wrap it in quotes (and escape quotes and newlines). One must use PARI: |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
#include <stdlib.h> |
#include <stdlib.h> |
||
#include <pari/pari.h> |
#include <pari/pari.h> |
||
Line 824: | Line 824: | ||
pari_printf("%Ps", vec); |
pari_printf("%Ps", vec); |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">$n = scalar <>; |
||
do_stuff(scalar <>) for 1..$n; |
do_stuff(scalar <>) for 1..$n; |
||
sub do_stuff { print $_[0] }</ |
sub do_stuff { print $_[0] }</syntaxhighlight> |
||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
<!--< |
<!--<syntaxhighlight lang="phix">(notonline)--> |
||
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (file i/o)</span> |
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (file i/o)</span> |
||
<span style="color: #004080;">sequence</span> <span style="color: #000000;">stack</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span> |
<span style="color: #004080;">sequence</span> <span style="color: #000000;">stack</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span> |
||
Line 862: | Line 862: | ||
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"===\n"</span><span style="color: #0000FF;">)</span> |
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"===\n"</span><span style="color: #0000FF;">)</span> |
||
<span style="color: #000000;">pop_all</span><span style="color: #0000FF;">()</span> |
<span style="color: #000000;">pop_all</span><span style="color: #0000FF;">()</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
(or more accurately the final state of the console) |
(or more accurately the final state of the console) |
||
Line 877: | Line 877: | ||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
<syntaxhighlight lang="powershell"> |
|||
<lang PowerShell> |
|||
# script.ps1 |
# script.ps1 |
||
Line 884: | Line 884: | ||
# ./script file.txt |
# ./script file.txt |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
<syntaxhighlight lang="prolog"> |
|||
<lang Prolog> |
|||
number_of_lines(Num) :- |
number_of_lines(Num) :- |
||
current_input(In), |
current_input(In), |
||
Line 908: | Line 908: | ||
number_of_lines(Num), |
number_of_lines(Num), |
||
input_lines_for_num(Num, []). |
input_lines_for_num(Num, []). |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 929: | Line 929: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
< |
<syntaxhighlight lang="python">try: input = raw_input |
||
except: pass |
except: pass |
||
Line 938: | Line 938: | ||
for x in range(linecount): |
for x in range(linecount): |
||
line = input() |
line = input() |
||
do_stuff(line)</ |
do_stuff(line)</syntaxhighlight> |
||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="racket">#lang racket |
||
(define (do-stuff str) |
(define (do-stuff str) |
||
(displayln str)) |
(displayln str)) |
||
Line 953: | Line 953: | ||
(for ([i (in-range line-count)]) |
(for ([i (in-range line-count)]) |
||
(do-stuff (read-line)))</ |
(do-stuff (read-line)))</syntaxhighlight> |
||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
Line 960: | Line 960: | ||
Short version: |
Short version: |
||
<lang |
<syntaxhighlight lang="raku" line>say get for ^get;</syntaxhighlight> |
||
Verbose version: |
Verbose version: |
||
<lang |
<syntaxhighlight lang="raku" line>sub do-stuff ($line) { |
||
say $line; |
say $line; |
||
} |
} |
||
Line 972: | Line 972: | ||
my $line = get; |
my $line = get; |
||
do-stuff $line; |
do-stuff $line; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
Programming note: this method was chosen because the standard input may be identical to the standard output. |
Programming note: this method was chosen because the standard input may be identical to the standard output. |
||
< |
<syntaxhighlight lang="rexx">/*REXX program writes a number of lines from the default input file (C.L.). */ |
||
#=linein() /*number of lines to be read from C.L. */ |
#=linein() /*number of lines to be read from C.L. */ |
||
Line 984: | Line 984: | ||
exit /*stick a fork in it, we're all done. */ |
exit /*stick a fork in it, we're all done. */ |
||
/*────────────────────────────────────────────────────────────────────────────*/ |
/*────────────────────────────────────────────────────────────────────────────*/ |
||
stuff: do k=1 for #; call lineout ,x.k; end; return</ |
stuff: do k=1 for #; call lineout ,x.k; end; return</syntaxhighlight> |
||
{{out|output|text= where showing the input and the output to the terminal:}} |
{{out|output|text= where showing the input and the output to the terminal:}} |
||
<pre> |
<pre> |
||
Line 997: | Line 997: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
# Project : Input/Output for Lines of Text |
# Project : Input/Output for Lines of Text |
||
Line 1,014: | Line 1,014: | ||
see lines[i] + nl |
see lines[i] + nl |
||
next |
next |
||
</syntaxhighlight> |
|||
</lang> |
|||
Input: |
Input: |
||
<pre> |
<pre> |
||
Line 1,030: | Line 1,030: | ||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang="ruby">def do_stuff(line) |
||
puts line |
puts line |
||
end |
end |
||
Line 1,038: | Line 1,038: | ||
line = gets |
line = gets |
||
do_stuff(line) |
do_stuff(line) |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
< |
<syntaxhighlight lang="scala">// Input/Output for Lines of Text |
||
object IOLines extends App { |
object IOLines extends App { |
||
private val in = scala.io.StdIn |
private val in = scala.io.StdIn |
||
Line 1,052: | Line 1,052: | ||
doStuff(word) |
doStuff(word) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
< |
<syntaxhighlight lang="tcl">proc do_stuff {line} { |
||
puts $line |
puts $line |
||
} |
} |
||
Line 1,061: | Line 1,061: | ||
foreach - [lrepeat [gets stdin] dummy] { |
foreach - [lrepeat [gets stdin] dummy] { |
||
do_stuff [gets stdin] |
do_stuff [gets stdin] |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Ursa}}== |
=={{header|Ursa}}== |
||
< |
<syntaxhighlight lang="ursa"># |
||
# input/output for lines of text |
# input/output for lines of text |
||
# |
# |
||
Line 1,084: | Line 1,084: | ||
out lines<i> endl console |
out lines<i> endl console |
||
end for |
end for |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
This assumes that both Stdin and Stdout are connected to a terminal. |
This assumes that both Stdin and Stdout are connected to a terminal. |
||
< |
<syntaxhighlight lang="ecmascript">import "io" for Stdin |
||
var output = Fn.new { |lines| System.print(lines.join("\n")) } |
var output = Fn.new { |lines| System.print(lines.join("\n")) } |
||
Line 1,097: | Line 1,097: | ||
for (i in 0...n) lines[i] = Stdin.readLine() |
for (i in 0...n) lines[i] = Stdin.readLine() |
||
System.print() |
System.print() |
||
output.call(lines)</ |
output.call(lines)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,114: | Line 1,114: | ||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
The input file must be redirected on the command line, for example: iotext <iotext.txt |
The input file must be redirected on the command line, for example: iotext <iotext.txt |
||
< |
<syntaxhighlight lang="xpl0">string 0; |
||
proc PrintLn(Str); \"method" to print a line of text |
proc PrintLn(Str); \"method" to print a line of text |
||
Line 1,133: | Line 1,133: | ||
Line(I):= 0; |
Line(I):= 0; |
||
PrintLn(Line); |
PrintLn(Line); |
||
]</ |
]</syntaxhighlight> |
||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
File ff.zkl: |
File ff.zkl: |
||
< |
<syntaxhighlight lang="zkl">numLines:=File.stdin.readln().strip().toInt(); |
||
text:=File.stdin.readln(numLines); |
text:=File.stdin.readln(numLines); |
||
text.apply(File.stdout.write);</ |
text.apply(File.stdout.write);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
Revision as of 16:27, 27 August 2022
- Task
The first line contains the number of lines to follow, followed by that number of lines of text on STDIN.
Write to STDOUT each line of input by passing it to a method as an intermediate step. The code should demonstrate these 3 things.
- Sample input with corresponding output
Input
3 hello hello world Pack my Box with 5 dozen liquor jugs
Output
hello hello world Pack my Box with 5 dozen liquor jugs
- Related tasks
11l
F do_stuff(words)
print(words)
V linecount = Int(input())
L 1..linecount
V line = input()
do_stuff(line)
Action!
The user must type in the monitor the following command after compilation and before running the program!
SET EndProg=*
CARD EndProg ;required for ALLOCATE.ACT
INCLUDE "D2:ALLOCATE.ACT" ;from the Action! Tool Kit. You must type 'SET EndProg=*' from the monitor after compiling, but before running this program!
PROC Main()
DEFINE PTR="CARD"
BYTE i,nLines
PTR ARRAY lines(256)
CHAR ARRAY line(256),p
AllocInit(0)
Put(125) PutE()
nLines=InputB()
IF nLines=0 THEN RETURN FI
FOR i=0 TO nLines-1
DO
InputS(line)
p=Alloc(line(0)+1)
MoveBlock(p,line,line(0)+1)
lines(i)=p
OD
PutE()
FOR i=0 TO nLines-1
DO
p=lines(i)
PrintE(p)
OD
FOR i=0 TO nLines-1
DO
p=lines(i)
Free(p,p(0)+1)
lines(i)=0
OD
nLines=0
RETURN
- Output:
Screenshot from Atari 8-bit computer
3 hello hello world Pack my Box with 5 dozen liquor jugs hello hello world Pack my Box with 5 dozen liquor jugs
Ada
--
-- The first line contains the number of lines to follow, followed by that
-- number of lines of text on STDIN.
--
-- Write to STDOUT each line of input by passing it to a method as an
-- intermediate step. The code should demonstrate these 3 things.
--
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
procedure Main is
Num_Lines : Integer;
begin
Get(Num_Lines);
Skip_Line;
for I in 1..Num_Lines loop
Put_Line(Get_Line);
end loop;
end Main;
Input:
3 hello hello world Pack my Box with 5 dozen liquor jugs
- Output:
hello hello world Pack my Box with 5 dozen liquor jugs
ALGOL 68
# outputs line plus a newline #
PROC show line = ( STRING line )VOID:
print( ( line, newline ) );
# copy the lines with an loop with an anonymous loop counter #
# as the loop limit is evaluated only once, we can read the #
# number of lines in the "TO" part #
TO ( INT n; read( ( n, newline ) ); n )
DO
show line( ( STRING line; read( ( line, newline ) ); line ) )
OD
ALGOL W
begin
% outputs line on a newline %
procedure showLine ( string(80) value line ); write( line );
string(80) line;
integer lineCount;
read( lineCount );
for lineNumber := 1 until lineCount do begin
read( line );
showLine( line )
end for_lineNumber
end.
Applesoft BASIC
100 GOSUB 230"INPUT LINE"
110 LET N = VAL (L$) - 1
120 IF N < 0 THEN END
130 DIM L$(N)
140 FOR I = 0 TO N
150 GOSUB 230"INPUT LINE"
160 LET L$(I) = L$
170 NEXT I
190 FOR I = 0 TO N
200 PRINT L$(I)
210 NEXT
220 END
230 LET L$ = ""
240 LET C$ = ""
250 FOR C = 0 TO 1 STEP 0
260 LET L$ = L$ + C$
270 GET C$
280 PRINT CHR$ (0)C$;
290 LET C = C$ = CHR$ (13)
300 NEXT C
310 LET C = FRE (0)
320 RETURN
Input
3 hello hello world Pack my Box with 5 dozen liquor jugs
- Output:
hello hello world Pack my Box with 5 dozen liquor jugs
AWK
# syntax: GAWK -f INPUT_OUTPUT_FOR_LINES_OF_TEXT.AWK
BEGIN {
getline n
while (i++ < n) {
getline
str = sprintf("%s%s\n",str,$0)
}
printf("%s",str)
exit(0)
}
Batch File
@echo off
setlocal enabledelayedexpansion
set /p lines=
for /l %%i in (1,1,%lines%) do set /p line%%i=
cls
for /l %%i in (1,1,%lines%) do echo !line%%i!
pause>nul
- Input:
3 line 1 this is line 2 line 3 is the longest
- Output:
line 1 this is line 2 line 3 is the longest
C
#include<stdlib.h>
#include<stdio.h>
#define LEN 100 /* Max string length */
int main()
{
char **list;
int num, i;
scanf("%d",&num);
list = (char**)malloc(num*sizeof(char*));
for(i=0;i<num;i++)
{
list[i] = (char*)malloc(LEN*sizeof(char));
fflush(stdin);
fgets(list[i],LEN,stdin);
}
printf("\n");
for(i=0;i<num;i++)
{
printf("%s",list[i]);
}
return 0;
}
Alternative code:
This program will read a number through STDIN... well, trough pipeline:
$ echo n | io
where "n" is the number of lines it will print.
When the total number of lines entered has been reached, it will display a message indicating that you must enter a number.
// Programa IO.C
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int check_number(const char *s){
const char*t=s;
while(*t!='\n'){
if( !isdigit(*t) ) return 0;
++t;
}
return 1;
}
int main( int argc, char *argv[] )
{
char s[100],r[10];
int n=0;
FILE *fp;
fgets(s,100,stdin); // input trough stdin.
if( (fp = fopen("temporal.txt","r"))!=NULL){
fgets(r,10,fp);
n=atoi(r);
if(n>0){
--n;
fclose(fp);
fp=fopen("temporal.txt","w");
sprintf(r,"%d",n);
fputs(r,fp);
fclose(fp);
printf("%s\n",s);
}else{
fclose(fp);
remove("temporal.txt");
perror("I need a number of the lines here!\n");
}
}else{
if(check_number((const char*)s)){
fp=fopen("temporal.txt","w");
fputs(s,fp);
fclose(fp);
}else{
perror("I need a number of the lines here!\n");
}
}
return 0;
}
- Output:
$ echo 3 | ./io $ echo "hola" | ./io hola $ echo "hola mundo" | ./io hola mundo $ echo "lore ipsum et la concha de la lora latinus" | ./io lore ipsum et la concha de la lora latinus $ echo "lore ipsum et la concha de la lora latinus" | ./io I need a number of the lines here! : Success $
C++
#include <iostream>
#include <vector>
int main()
{
// read the number of lines
int numberOfLines;
std::cin >> numberOfLines;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // skip to next line
// read the lines
std::vector<std::string> lines(numberOfLines);
for(int i = 0; i < numberOfLines; ++i)
{
std::getline(std::cin, lines[i]);
}
// print the lines
for(const auto& value : lines)
{
std::cout << value << "\n";
}
}
Input:
3 hello hello world Pack my Box with 5 dozen liquor jugs
- Output:
hello hello world Pack my Box with 5 dozen liquor jugs
D
void main() {
import std.stdio, std.conv, std.string;
enum doStuff = (in string line) => line.write;
foreach (_; 0 .. readln.strip.to!uint)
doStuff(readln.idup);
}
Delphi
program Output_for_Lines_of_Text;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
function QueryIntNumber(): Integer;
var
val: string;
begin
Result := 0;
repeat
Writeln('Digite a number(Enter to confirm):');
Readln(val);
if not TryStrToInt(val, Result) then
begin
Writeln('"', val, '" is not a valid number.');
Continue;
end;
if Result <= 0 then
begin
Writeln('"', val, '" must be greater then 0');
Continue;
end;
until Result > 0;
end;
var
n_lines, i: integer;
lines, line: string;
begin
lines := '';
n_lines := QueryIntNumber;
for i := 1 to n_lines do
begin
Readln(line);
if i > 1 then
lines := lines + #10;
lines := lines + line;
end;
Writeln(lines);
Readln;
end.
- Output:
Digite a number(Enter to confirm): 3 hello hello world Pack my Box with 5 dozen liquor jugs hello hello world Pack my Box with 5 dozen liquor jugs
Factor
USING: io kernel strings ;
IN: input-output
GENERIC: do-stuff ( obj -- )
M: string do-stuff print ;
readln drop [ do-stuff ] each-line
Free Pascal
This requires FPC – the FreePascal compiler – to be in a configuration enabling the use ob objects.
program head(input, output, stdErr);
type
obj = object
public
procedure method(const s: string); static;
end;
procedure obj.method(const s: string);
begin
writeLn(s);
end;
var
numberOfLines: integer;
line: string;
begin
readLn(numberOfLines);
for numberOfLines := numberOfLines downto 1 do
begin
readLn(line);
obj.method(line);
end;
end.
FreeBASIC
' FB 1.05.0 Win64
Sub printLines(lines() As String)
For i As Integer = LBound(lines) To UBound(lines)
Print lines(i)
Next
End Sub
Dim As UInteger n
Input "", n
Dim lines(1 To n) As String
For i As Integer = 1 To n
Line Input lines(i)
Next
Print
printLines lines()
Sleep
- Output:
3 hello hello world Pack my Box with 5 dozen liquor jugs hello hello world Pack my Box with 5 dozen liquor jugs
Go
package main
import (
"bufio"
"fmt"
"io"
"log"
"os"
)
func main() {
// Often we'd already have wrapped os.Stdin (or some other
// io.Reader, like an *os.File) in a bufio.Reader by this point
// and we'd use fmt.Fscanln() on that reader instead.
var lines int
n, err := fmt.Scanln(&lines)
if n != 1 || err != nil {
log.Fatal(err)
}
// Use a bufio.Scanner. This uses a SplitFunc which we can choose
// or provide our own that splits or otherwise pre-processes the
// input into tokens however we like.
//
// Could also just use bufio.ReadString('\n') but a Scanner
// with ScanLines matches (and removes) `\r?\n$` and is more
// general purpose.
//
// Normally the loop would be just:
// for scanner.Scan() {
// // use scanner.Text() or scanner.Bytes()
// }
// and we'd loop until the scan indicated EOF. But for this task
// we've got an explictly specified number of lines to read.
scanner := bufio.NewScanner(os.Stdin)
scanner.Split(bufio.ScanLines) // not needed, this is the default
for ; scanner.Scan() && lines > 0; lines-- {
doStuff(scanner.Text())
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
// Check for too few lines, normally not needed
if lines > 0 {
log.Fatalln("early", io.EOF)
}
}
func doStuff(line string) {
fmt.Println(line)
}
Haskell
import Control.Monad
main = do
number <- getLine
input <- replicateM (read number) getLine
mapM_ putStrLn input
Input:
3 hello hello world Pack my Box with 5 dozen liquor jugs
- Output:
hello hello world Pack my Box with 5 dozen liquor jugs
J
[for number pairs links to this page.]
Example in bash. jconsole is on the PATH.
$ cat <<EOF | jconsole -js '2!:55@:0:@:(; (1!:2) 4:)@:(}. {.~ _ ". [: }: 0&{::)@:(<;.2)@:(1!:1) 3'
> 3
> hello
> hello world
> Pack my Box with 5 dozen liquor jugs
> EOF
hello
hello world
Pack my Box with 5 dozen liquor jugs
From the dictionary of j (DOJ) the data flow for the fork (f g h) is
5. Forks
As illustrated above, an isolated sequence of three verbs is called a fork; its monadic and dyadic cases are defined by:
g / \ f h | | y y g / \ f h / \ / \ x y x y
Reading from left to right
2!:55 is exit. 0: is a verb that returns 0 for any input. So now we know the script will terminate the j session with successful status.
What does it do before this? 1!:2 is "write to file", with left argument x as the data to write, and the right argument y specifies the file. 4: is a verb returning 4 for any input. File 4 is stdout.
;
is "raze". The fork
(; (1!:2) 4:)
writes data to stdout.
Good!
What is the data? (}. {.~ _ ". [: }: 0&{::) Because it has an odd number of verbs, this expresses a fork. And because {:: (fetch) is in the fork the right argument y is a vector of boxes. We know that the data has a number followed by some lines of text. Let's read the fork from left to right. The second verb, {. is "take" modified by the ~ "passive" adverb to swap arguments. Take uses a shape argument on left (x), and the data to take as y. Remembering the passive effect, the data to which take applies will be the beheaded vector of boxes---beheading removes the first line which is the number, and the fork to the right of {.~ computes the shape. Now looking at the fourth verb, ". (numbers) the default in case of error is _ (infinity meaning "all" when used along a shape dimension to take) and the data for numbers is the curtailed }: content of the first box (index origin 0). 0 is & (bonded also known as curried) to fetch. Curtailing removes the line feed. Since this gives a list of boxes, but we need to display literal data, raze "unboxes" one level of boxing. Good, if we have a list of boxed lines of input.
(<;.2)@:(1!:1) 3 (<;.2) is "< (box) ;. (cut) 2 . The 2 specifies the last item of the data as the fret, and to preserve the frets. (1!:1) 3 is "read stdin".
I chose to connect the parts into a single verb using @: (at).
With predefined verbs from standard profile we can write the simpler, more readable for native English speakers, and robust sentence which ensures a final linefeed fret and discards the frets with <;._2
exit@:0:@:(smoutput&>)@:(}. {.~ _ ". 0&{::)@:cutLF@:(1!:1) 3
Cheers! That's tacit j.
Java
import java.util.Scanner;
public class Main {
public static void doStuff(String word){
System.out.println(word);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = Integer.parseInt(in.nextLine()); //doesn't use nextInt() so nextLine doesn't just read newline character
for(int i=0; i<n; i++){
String word = in.nextLine();
doStuff(word);
}
}
}
Julia
function dosomething(words)
print(words)
end
nlines = parse.(Int, readline())
for _ in 1:nlines
words = readline()
dosomething(words)
end
Kotlin
// version 1.1
fun output(lines: Array<String>) = println(lines.joinToString("\n"))
fun main(args: Array<String>) {
println("Enter the number of lines to be input followed by those lines:\n")
val n = readLine()!!.toInt()
val lines = Array(n) { readLine()!! }
println("\nThe lines you entered are:\n")
output(lines)
}
- Output:
Enter the number of lines to be input followed by those lines: 3 hello hello world Pack my Box with 5 dozen liquor jugs The lines you entered are: hello hello world Pack my Box with 5 dozen liquor jugs
Lua
function show (t)
for _, line in pairs(t) do print(line) end
end
local lineTable, numLines = {}, io.read()
for i = 1, numLines do table.insert(lineTable, io.read()) end
show(lineTable)
Nanoquery
// get how many lines the user wants
amount = int(input())
// loop through and get lines
lines = {}
for i in range(1, amount)
lines.append(input())
end
// output the lines that the user entered
println
for line in lines
println line
end
- Output:
3 this is a test the program will read three lines from the console this is the third line this is a test the program will read three lines from the console this is the third line
Nim
import strutils
proc write(line: string) =
echo line
let lineCount = stdin.readLine.parseInt()
for _ in 1..lineCount:
let line = stdin.readLine()
line.write()
Objeck
use System.IO.File;
class Rosetta {
function : Main(args : String[]) ~ Nil {
in : FileReader;
leaving {
if(in <> Nil) {
in->Close();
};
};
if(args->Size() = 1) {
in := FileReader->New(args[0]);
i := in->ReadString()->ToInt();
while(i-- <> 0) {
in->ReadString()->PrintLine();
};
};
}
}
PARI/GP
This task is not possible to implement directly in GP: for input()
to take a string the user would have to wrap it in quotes (and escape quotes and newlines). One must use PARI:
#include <stdio.h>
#include <stdlib.h>
#include <pari/pari.h>
int main(void);
int
main()
{
int i, n, s;
GEN vec;
// 1 MB stack, not using prime table
pari_init(1000000, 0);
scanf("%d", &n);
GEN vec = cgetg(n+1, t_VEC);
for (i = 1; i <= n; i++) {
if (1 != scanf("%s", &s)) abort();
gel(vec, i) = strtoGENstr(s);
}
pari_printf("%Ps", vec);
return 0;
}
Perl
$n = scalar <>;
do_stuff(scalar <>) for 1..$n;
sub do_stuff { print $_[0] }
Phix
without js -- (file i/o) sequence stack = {} procedure push(string line) stack = append(stack,line) end procedure procedure pop_all() while length(stack) do puts(1,stack[1]) stack = stack[2..$] end while end procedure string line = gets(0) sequence r = scanf(trim(line),"%d") if length(r)!=1 then puts(1,"input not a number\n") abort(0) end if puts(1,"\n") for i=1 to r[1][1] do line = gets(0) push(line) puts(1,"\n") end for puts(1,"===\n") pop_all()
- Output:
(or more accurately the final state of the console)
3 one two three === one two three
PowerShell
# script.ps1
$in = Get-Content $args[0]
$in[1..($in.Count-1)]
# ./script file.txt
Prolog
number_of_lines(Num) :-
current_input(In),
read_line_to_codes(In, Line),
number_codes(Num, Line).
input_lines_for_num(0, ListOfLines) :-
format('~nThe lines you entered were: ~n~n'),
maplist(format('~w~n'), ListOfLines).
input_lines_for_num(Num, CurrentLines) :-
Num > 0,
Num1 is Num - 1,
current_input(In),
read_line_to_codes(In, Line),
atom_codes(LineAsAtom, Line),
append(CurrentLines, [LineAsAtom], MoreLines),
input_lines_for_num(Num1, MoreLines).
lines :-
number_of_lines(Num),
input_lines_for_num(Num, []).
- Output:
2 ?- lines. |: 3 line 1 line 2 line 3 The lines you entered were: line 1 line 2 line 3 true ; false. 3 ?-
Python
try: input = raw_input
except: pass
def do_stuff(words):
print(words)
linecount = int(input())
for x in range(linecount):
line = input()
do_stuff(line)
Racket
#lang racket
(define (do-stuff str)
(displayln str))
;(define line-count (read)) ;reads all kind of things
(define line-count (string->number ;only reads numbers
(string-trim
(read-line))))
(for ([i (in-range line-count)])
(do-stuff (read-line)))
Raku
(formerly Perl 6)
Short version:
say get for ^get;
Verbose version:
sub do-stuff ($line) {
say $line;
}
my $n = +get;
for ^$n {
my $line = get;
do-stuff $line;
}
REXX
Programming note: this method was chosen because the standard input may be identical to the standard output.
/*REXX program writes a number of lines from the default input file (C.L.). */
#=linein() /*number of lines to be read from C.L. */
do j=1 for #; x.j=linein(); end /*obtain input lines from stdin (C.L.).*/
call stuff /*call the STUFF subroutine for writes.*/
exit /*stick a fork in it, we're all done. */
/*────────────────────────────────────────────────────────────────────────────*/
stuff: do k=1 for #; call lineout ,x.k; end; return
- output where showing the input and the output to the terminal:
3 ◄■■■■■■■ user input aaa ◄■■■■■■■ user input bbb ◄■■■■■■■ user input ccc ◄■■■■■■■ user input aaa bbb ccc
Ring
# Project : Input/Output for Lines of Text
see "n = "
give n
lines = list(number(n))
for i = 1 to n
see "lines[" + i + "] = " + nl
give lines[i]
next
see nl
printlines(lines)
func printlines(lines)
for i = 1 to len(lines)
see lines[i] + nl
next
Input:
3 hello hello world Pack my Box with 5 dozen liquor jugs
Output:
hello hello world Pack my Box with 5 dozen liquor jugs
Ruby
def do_stuff(line)
puts line
end
n = gets.to_i
n.times do
line = gets
do_stuff(line)
end
Scala
// Input/Output for Lines of Text
object IOLines extends App {
private val in = scala.io.StdIn
private val n = in.readInt()
private def doStuff(word: String): Unit = println(word)
for (_ <- 0 until n) {
val word = in.readLine()
doStuff(word)
}
}
Tcl
proc do_stuff {line} {
puts $line
}
foreach - [lrepeat [gets stdin] dummy] {
do_stuff [gets stdin]
}
Ursa
#
# input/output for lines of text
#
# get how many lines the user wants
decl int amount
set amount (in int console)
# loop through and get lines
decl string<> lines
decl int i
for (set i 0) (< i amount) (inc i)
append (in string console) lines
end for
# output the lines that the user entered
out endl console
for (set i 0) (< i amount) (inc i)
out lines<i> endl console
end for
Wren
This assumes that both Stdin and Stdout are connected to a terminal.
import "io" for Stdin
var output = Fn.new { |lines| System.print(lines.join("\n")) }
var n = Num.fromString(Stdin.readLine())
if (!n || !n.isInteger || n < 1) Fiber.abort("Number of lines must be a positive integer.")
var lines = List.filled(n, "")
for (i in 0...n) lines[i] = Stdin.readLine()
System.print()
output.call(lines)
- Output:
Sample input/output:
3 hello hello world Pack my Box with 5 dozen liquor jugs hello hello world Pack my Box with 5 dozen liquor jugs
XPL0
The input file must be redirected on the command line, for example: iotext <iotext.txt
string 0;
proc PrintLn(Str); \"method" to print a line of text
char Str;
[Text(0, Str);
CrLf(0);
];
char Line(1000);
int N, I, C;
for N:= 1 to IntIn(1) do
[I:= 0;
loop [repeat C:= ChIn(1) until C # $0D \CR\;
if C = $0A \LF\ then quit;
Line(I):= C;
I:= I+1;
];
Line(I):= 0;
PrintLn(Line);
]
zkl
File ff.zkl:
numLines:=File.stdin.readln().strip().toInt();
text:=File.stdin.readln(numLines);
text.apply(File.stdout.write);
- Output:
cat foo.txt | zkl ff hello hello world Pack my Box with 5 dozen liquor jugs