-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstdio.html
More file actions
616 lines (453 loc) · 14.6 KB
/
stdio.html
File metadata and controls
616 lines (453 loc) · 14.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
<title>言語別標準入出力</title>
<!--$ があるとMathjaxになってしまうので無理やりオフに -->
<div class="tex2jax_ignore">
各問題の入出力の受け取り方です。
ここでは、
<a href="http://yukicoder.me/problems/527">No.9001 標準入出力の練習問題(テスト用)</a>の問題を例にしております。
<h3 class="shadow">C++</h3>
<pre>
#include <iostream>
#include <string>
using namespace std;
int main() {
int a, b;
string s;
// 標準入力から、空白や改行で区切られた整数と文字列を読み込む。
cin >> a >> b >> s;
// 整数と文字列を空白で区切って、標準出力に書き出す。
cout << a + b << " " << s << endl;
return 0;
}
</pre>
data9824さん提供
<h3 class="shadow">C</h3>
<pre>
#include <stdio.h> // scanfとprintfを使うおまじない
int main(int argc, char *argv[]){
int A, B;
char S[11];
// 標準入力から読み込む(空白や改行で勝手に区切ってくれる)
// 逆に空白込みの文字列を読み込む場合は別の方法で読む必要がある。
scanf("%d%d%s", &A, &B, S);
// 標準出力に出力
printf("%d %s\n", A + B, S);
return 0;
}
</pre>
なおさん提供
<h3 class="shadow">Java</h3>
<pre>
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// 標準入力から読み込む際に、Scannerオブジェクトを使う。
Scanner sc = new Scanner(System.in);
// int 1つ分を読み込む
int a = sc.nextInt();
// int 1つ分を読み込む
int b = sc.nextInt();
// String 1つ分を読み込む
String s = sc.next();
// 標準出力に書き出す。
System.out.println((a + b) + " " + s);
}
}
</pre>
クラス名については <a href="https://yukicoder.me/help">https://yukicoder.me/help</a> を参照。
<h3 class="shadow">C#</h3>
<pre>
using System;
public class Program
{
static void Main()
{
string s = Console.ReadLine();
string[] t = s.Split(' ');
int a = int.Parse(t[0]);
int b = int.Parse(t[1]);
s = Console.ReadLine();
Console.WriteLine("{0} {1}", a + b, s);
}
}
</pre>
camypaperさん提供
<h3 class="shadow">D</h3>
<pre>
import std.stdio, std.conv, std.string, std.range, std.array,
std.algorithm;
void main() {
auto I = readln().strip().split().map!(to!int)().array();
auto S = readln().strip();
writeln( I.sum, " ", S );
}
</pre>
diginatuさん提供
<h3 class="shadow">Ruby</h3>
<pre>
A,B=gets.split.map(&:to_i)
print A+B,' ',gets
</pre>
cielさん提供
<h3 class="shadow">Python2 (PyPy2)</h3>
<pre>
# -*- coding: utf-8 -*-
# ↑の一行をかかないと日本語のコメントが書けないので注意です。
# 標準入力から一行分を読み出し、文字列として格納する。
first = raw_input()
# 読み込んだ文字列をスペースで分割する。
split_first = first.split()
# それぞれをint型に変換する。
A = int(split_first[0])
B = int(split_first[1])
# 慣れてくると この一行でよい
# A, B = map(int, raw_input().split())
#2行目を読み込む
S = raw_input()
# 標準出力に書き出す。
# カンマで区切るとスペースで分割してくれるので楽です。
print A + B, S
</pre>
<h3 class="shadow">Python3 (PyPy3)</h3>
<pre>
# 標準入力から一行分を読み出し、文字列として格納する。
first = input()
# 読み込んだ文字列をスペースで分割する
split_first = first.split()
# それぞれをint型に変換する
A = int(split_first[0])
B = int(split_first[1])
# 慣れてくると この一行でよい
# A, B = map(int, input().split())
# 参考: リストを読む際はlist()で覆ってやらないといけない
# L = list(map(int, input().split()))
#2行目を読み込む
S = input()
# 標準出力に書き出す。
# カンマで区切るとスペースで分割してくれるので楽です。
print(A + B, S)
</pre>
標準入力を一行分読み出し、文字列に格納する関数は、<br>
Python2ではraw_input()、Python3ではinput()です。<br>
Python2のinput()と同じ動きをする組込み関数はPython3には存在せず(※)、<br>
Python3にはraw_input()という名前の組み込み関数は存在しません。<br>
※eval(input())でエミュレートする案が有名か。<br>
printもpython3からは関数呼び出しになっているので注意(注:Python2でも<b>from __future__ import print_function</b>することでこの挙動に出来ます)
<br>
<h3 class="shadow">PHP</h3>
<pre>
<?php
//一行分を読み込む, 空白で分割してそれぞれ$aと$bの変数に入れる
list($a, $b) = explode(" ", trim(fgets(STDIN)));
$c = $a + $b;
//2行目を読み込む
$S = trim(fgets(STDIN));
//標準出力に書き出す。
printf("$c $S\n");
</pre>
最初に <?php をつけないといけないことに注意。最後の?>は必要ありません。
<h3 class="shadow">Perl</h3>
<pre>
#!/usr/bin/perl
# 1行読み込む
$N = <>;
# 末尾に改行が付いているので取り除く
chomp $N;
# 空白で分割する
($A, $B) = split /\s/, $N;
# 1行読み込む
$S = <>;
# 末尾に改行が付いているので取り除く
chomp $S;
# 標準出力に出力します
print $A + $B, " ", $S;
</pre>
なおさん提供
<h3 class="shadow">Perl 6</h3>
<pre>
# 1行読み込んで空白で分割
my ($A,$B) = get().split(' ');
# 1行読み込む
my $S = get();
# 計算して出力
say $A+$B, ' ', $S;
</pre>
なおさん提供
<h3 class="shadow">Scala</h3>
<pre>
import scala.io.StdIn.readLine
object Main {
def main(args: Array[String]){
val ab = readLine().split(" ").map(_.toInt)
val (a,b) = (ab(0),ab(1))
val s = readLine()
val n = a+b
println(s"$n $s")
}
}
</pre>
ともきさん提供
<h3 class="shadow">JavaScript</h3>
nodeコマンドなどで端末でする場合は、入力が終わりというシグナル<code>Ctrl+D</code>を押す必要がある。
<pre>
function Main(input) {
// inputにはすべての入力の文字列が与えられるので必要に応じて input.split("\n") などで分割する。
var data = input.split("\n")
var first_line = data[0].split(" ")
var second_line = data[1]
var c = parseInt(first_line[0]) + parseInt(first_line[1])
console.log(c + " " + second_line);
}
// Don't edit this line!
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
</pre>
CodeforcesではNode.jsではなくv8が使用されている。両対応になる入出力例は以下のとおり(ただし空行を正しく処理できない点は注意を要する)。
<!--MathJaxのため正しく表示できず://usr/bin/env node $0 $@;exit-->
<pre>
var main=function(){
var a=readline().split(' ').map(Number);
print(a[0]+a[1]+' '+readline());
};
/// IO ///
if(typeof process!=='undefined'){
//node.js
var print=function(x){
console.log(x);
}
var readline=(function(){
var T=[],cnt=0;
var stdin = process.openStdin();
stdin.setEncoding('utf8');
var input_fragment="";
stdin.on('data', function(input) {
var ref=(input_fragment+input).split("\n");
input_fragment=ref.pop();
for(var i=0;i<ref.length;i++){
if(ref[i]=='')continue;
T.push(ref[i]);
}
});
stdin.on('end', function(z) {
if(input_fragment){
var ref=(input_fragment+"\n").split("\n");
input_fragment=ref.pop();
for(var i=0;i<ref.length;i++){
if(ref[i]=='')continue;
T.push(ref[i]);
}
}
main();
});
return function(){
if(T.length<=cnt)return null;
return T[cnt++];
};
})();
}else{
//v8
main();
}
</pre>
cielさん提供
<h3 class="shadow">Go</h3>
<pre>
package main
import "fmt"
func main() {
var A, B int
var S string
fmt.Scan(&A, &B, &S)
fmt.Println(A+B, S)
}
</pre>
fmhrさん提供
<h3 class="shadow">Haskell</h3>
<pre>
-- <$>とか使う場合は必須。でも、7.10からはデフォルトで読み込まれるので不要。
import Control.Applicative
-- main、ここでIOモナドを完結させる。
main :: IO ()
-- do記法を使う。別に他の方法でもいいけど、読み込む物が多くなった場合は、
-- こっちの方がわかりやすいと思う。たぶん。
main = do
-- ----
-- 1行読み込んで、空白切りで配列に分割して、それぞれを数字に変換する。
-- readで変換される型は、main'での型指定によって決まる。
-- IO [a]
ab <- map read . words <$> getLine
-- ----
-- 単純に1行をStringとして読み込む。末尾改行は含まれない。
-- IO String
s <- getLine
-- ----
-- その他に、1行に数字一つだけであれば下記のようにする。
-- IO a
-- n <- read <$> getLine
-- ----
-- 読み込んだ値を別関数に渡して、戻り値を出力する。
-- 戻り値がIntの場合は、`print`を使う。
-- 戻り値がFloatの場合は、`Text.Printf.printf`を使う必要がある。
-- IO ()
putStrLn $ main' ab s
-- 実際に問題を解く関数main'、実際の名前は何でもいい。
-- ここの型指定でmainでのreadが何に変換されるが決まる。
-- IOモナドは持ち込まずに純粋な関数だけの世界にすると書きやすいと思う。
main' :: [Int] -> String -> String
main' ab s = (show . sum) ab ++ " " ++ s
</pre>
らっしー(raccy)さん提供
<h3 class="shadow">Nim</h3>
<pre>
#!/usr/bin/env nim
import strutils
var AB=readLine(stdin).split()
var n=parseInt(AB[0])+parseInt(AB[1])
echo($n&" "&readLine(stdin))
</pre>
cielさん提供
<h3 class="shadow">Rust</h3>
<pre>
fn getline() -> String{
let mut __ret=String::new();
std::io::stdin().read_line(&mut __ret).ok();
return __ret;
}
fn main(){
let s=getline();
let a:Vec<_>=s.trim().split(' ').collect();
let x:i32=a[0].parse().unwrap();
let y:i32=a[1].parse().unwrap();
print!("{} ",x+y);
println!("{}",getline());
}
</pre>
cielさん提供
<h3 class="shadow">Kotlin</h3>
<pre>
fun main(args: Array<String>){
var (a,b)=readLine()!!.split(" ").map(String::toInt)
print(a+b)
print(" ")
println(readLine())
}
</pre>
cielさん提供
<h3 class="shadow">Scheme</h3>
<pre>
#!/usr/bin/env gosh
; letは変数束縛の評価順が不定のためlet*を使う
(let* ((a (read)) (b (read)) (s (read)))
(write (+ a b))
(display " ")
(write s)
(newline)
)
</pre>
cielさん提供
<h3 class="shadow">Crystal</h3>
<pre>
#!/usr/bin/env crystal
s=gets
# sはnilである可能性があるので、ifで分岐させる
if s
a,b=s.split.map{|e|e.to_i}
print a+b
puts " "+gets.not_nil! # not_nil!で外すことも可能
end
</pre>
cielさん提供<br>
<br>
ただし、64bit整数の入力にはto_i64を使いますが、以下のようなおまじないを挿入する必要があります。
<pre>
lib C;fun strtoll(s: UInt8*,p: UInt8**,b: Int32): Int64;end
class String;def to_i64;C.strtoll(self,nil,10);end;end
</pre>
本件は <a href="https://github.com/crystal-lang/crystal/issues/9654">https://github.com/crystal-lang/crystal/issues/9654</a> にて議論されましたが解決は望めなくなりました。
<h3 class="shadow">OCaml</h3>
<pre>
Scanf.sscanf (read_line ()) "%d %d" (fun a b ->
print_int (a+b)
);;
print_string " "; print_string (read_line ()); print_newline ();;
</pre>
cielさん提供
<pre>
(*
OCaml 4.12から 'String.split_on_char'という便利な関数が利用できるようになったので、
例えば `read_line () |> String.split_on_char ' ' |> List.map int_of_string`
といったような書き方が可能になった。
(標準ライブラリではない `Str`を使ったりするような必要がなくなった)
とはいえ、4.12に対応しているような"Online Judge"はまれ(AtCoderではなぜか使える)なのだが、
この手の「新規で使えるようになった標準ライブラリの関数」といった類のものは、ほとんどOCamlで
書かれている。
例えば `String.split_on_char`ならば、次の行で定義されている。
https://github.com/ocaml/ocaml/blob/cd65210491ae60803fa804e6e77fa8c2788da81e/stdlib/string.ml#L235
なので、このコードをそのままコピーして動かすことは可能。
この手段で `Aizu Online Judge`なんかのフ**キンなバージョンのOCamlでも気軽に書くことができる。
*)
let split_on_char sep s =
let r = ref [] in
let j = ref (String.length s) in
for i = String.length s - 1 downto 0 do
if String.unsafe_get s i = sep then begin
r := String.sub s (i + 1) (!j - i - 1) :: !r;
j := i
end
done;
String.sub s 0 !j :: !r;;
(*
もちろん、スペース空けではない単体の要素は単純に `read_int ()`
してあげてもよい (内部的な挙動は `read_line () |> int_of_string `) *)
let () =
read_int () |> solve;;
(*
Scanf.scanfを使う場合は、`Scanf.scanf " %d" (fun x -> x)`といったイディオムが使われることが多い。
*)
let scan_int () = Scanf.scanf " %d" (fun x -> x);;
</pre>
eseharaさん提供
<h3 class="shadow">Fortran</h3>
<pre>
implicit none
integer::a,b
character(99)::s
read(*,*) a,b,s
write(*,'(i0," ",a)') a+b,trim(s)
end
</pre>
cielさん提供
<h3 class="shadow">F#</h3>
<!--MathJaxのため正しく表示できず://usr/bin/env fsharpi $0 $@;exit-->
<pre>
open System;
let a:String array=Console.ReadLine().Split(' ')
Console.Write(int(a.[0])+int(a.[1]))
Console.WriteLine(" "+Console.ReadLine())
</pre>
cielさん提供
<h3 class="shadow">Kuin</h3>
<pre>
func main()
var a: int :: cui@inputInt()
var b: int :: cui@inputInt()
var s: []char :: cui@inputStr()
do cui@print("\{a + b} \{s}\n")
end func
</pre>
<h3 class="shadow">TypeScript</h3>
<pre>
function main(input: string): void {
const lines = input.split(/\n/);
const firstLine = lines[0].split(/\s/);
const A = parseInt(firstLine[0]);
const B = parseInt(firstLine[1]);
const secondLine = lines[1];
const S = secondLine;
console.log(A + B, S);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
</pre>
基本的に<a href="https://yukicoder.me/wiki/stdio#:~:text=JavaScript">JavaScript</a>のnodeでのやり方と同じです<br />
<h3 class="shadow">Whitespace</h3>
<pre>
</pre>
</div>