---
title: 程式輸入輸出範例
tags: code, vb.net, python, ruby, java
---
:::info
Windows 環境請使用 CMD 作為終端機執行程式碼與編譯。
:::
# StdIn 範例
## DOMjudge 與本地 stdin 測試方式
DOMjudge 執行程式時,會把測試資料送到程式的標準輸入(stdin)。在 DOMjudge 介面上通常只需要上傳 source code 檔案,不需要在程式中開啟 `in.txt` 或其他固定檔名。
本地環境可以先把範例測資存成 `in.txt`,再用重新導向模擬 DOMjudge 的輸入方式:
```shell=
$ python3 main.py < in.txt
$ gcc main.c -o main
$ ./main < in.txt
$ g++ main.cpp -o main
$ ./main < in.txt
$ javac Main.java
$ java Main < in.txt
```
:::danger
Online Judge 的輸出必須和題目要求完全一致,請不要多印提示文字,例如 `請輸入數字:`。
:::
## Online Judge 常見輸入格式
常見的輸入格式大致可分為:
- 固定行數:題目明確指定輸入格式與行數。
- 不定行數:題目要求讀到特定條件,或一直讀到 EOF(End of File,檔案結束)。
以下範例用同一組小題型示範 Python 3.9、C、C++、Java 的寫法。片段重點是讀取 stdin 與輸出 stdout,可依題目邏輯替換中間的計算。
### 固定行數:單行單值
讀入一個整數 `year`,輸出 `year - 1911`。
範例輸入:
```=
2008
```
範例輸出:
```=
97
```
Python 3.9:
```python=
year = int(input())
print(year - 1911)
```
C:
```c=
#include <stdio.h>
int main(void) {
int year;
scanf("%d", &year);
printf("%d\n", year - 1911);
return 0;
}
```
C++:
```cpp=
#include <iostream>
using namespace std;
int main() {
int year;
cin >> year;
cout << year - 1911 << '\n';
return 0;
}
```
Java:
```java=
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int year = sc.nextInt();
System.out.println(year - 1911);
}
}
```
### 固定行數:單行多值
讀入同一行的多個整數,輸出總和。
範例輸入:
```=
2 3 4
```
範例輸出:
```=
9
```
Python 3.9:
```python=
nums = list(map(int, input().split()))
print(sum(nums))
```
C:
```c=
#include <stdio.h>
int main(void) {
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
printf("%d\n", a + b + c);
return 0;
}
```
C++:
```cpp=
#include <iostream>
using namespace std;
int main() {
int a, b, c;
cin >> a >> b >> c;
cout << a + b + c << '\n';
return 0;
}
```
Java:
```java=
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
System.out.println(a + b + c);
}
}
```
### 固定行數:第一行指定資料筆數
第一行讀入 `n`,接著讀取 `n` 筆資料。
範例輸入:
```=
3
1 2
10 20
-3 4
```
範例輸出:
```=
3
30
1
```
Python 3.9:
```python=
n = int(input())
for _ in range(n):
a, b = map(int, input().split())
print(a + b)
```
C:
```c=
#include <stdio.h>
int main(void) {
int n, a, b;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d %d", &a, &b);
printf("%d\n", a + b);
}
return 0;
}
```
C++:
```cpp=
#include <iostream>
using namespace std;
int main() {
int n, a, b;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a >> b;
cout << a + b << '\n';
}
return 0;
}
```
Java:
```java=
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println(a + b);
}
}
}
```
### 不定行數:讀到特定條件結束
每行讀入兩個整數,直到讀到 `0 0` 結束,不處理結束那一行。
範例輸入:
```=
1 2
10 20
0 0
```
範例輸出:
```=
3
30
```
Python 3.9:
```python=
while True:
a, b = map(int, input().split())
if a == 0 and b == 0:
break
print(a + b)
```
C:
```c=
#include <stdio.h>
int main(void) {
int a, b;
while (scanf("%d %d", &a, &b) == 2) {
if (a == 0 && b == 0) {
break;
}
printf("%d\n", a + b);
}
return 0;
}
```
C++:
```cpp=
#include <iostream>
using namespace std;
int main() {
int a, b;
while (cin >> a >> b) {
if (a == 0 && b == 0) {
break;
}
cout << a + b << '\n';
}
return 0;
}
```
Java:
```java=
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNextInt()) {
int a = sc.nextInt();
int b = sc.nextInt();
if (a == 0 && b == 0) {
break;
}
System.out.println(a + b);
}
}
}
```
### 不定行數:讀到 EOF
測資沒有先給行數,也沒有結束符號時,就持續讀到 EOF。
範例輸入:
```=
22 1
23 1
24 1
```
範例輸出:
```=
23
24
25
```
Python 3.9:
```python=
import sys
for line in sys.stdin:
a, b = map(int, line.split())
print(a + b)
```
C:
```c=
#include <stdio.h>
int main(void) {
int a, b;
while (scanf("%d %d", &a, &b) == 2) {
printf("%d\n", a + b);
}
return 0;
}
```
C++:
```cpp=
#include <iostream>
using namespace std;
int main() {
int a, b;
while (cin >> a >> b) {
cout << a + b << '\n';
}
return 0;
}
```
Java:
```java=
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNextInt()) {
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println(a + b);
}
}
}
```
### 資料型態轉換與逗號分隔
從 stdin 讀進來的資料一開始通常都是字串;題目要求整數、小數或其他型態時,要先轉型。若資料使用逗號分隔,就不能只用空白分隔的寫法。
範例輸入:
```=
1,2,3
```
範例輸出:
```=
6
```
Python 3.9:
```python=
line = input()
a, b, c = map(int, line.split(","))
print(a + b + c)
nums = [int(x) for x in line.split(",")]
```
C:
```c=
#include <stdio.h>
int main(void) {
int a, b, c;
scanf("%d,%d,%d", &a, &b, &c);
printf("%d\n", a + b + c);
return 0;
}
```
C++:
```cpp=
#include <iostream>
using namespace std;
int main() {
int a, b, c;
char comma;
cin >> a >> comma >> b >> comma >> c;
cout << a + b + c << '\n';
return 0;
}
```
Java:
```java=
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] parts = sc.nextLine().split(",");
int sum = 0;
for (String part : parts) {
sum += Integer.parseInt(part);
}
System.out.println(sum);
}
}
```
## 其他既有語言格式速查
以下補充本文件其他語言常見的輸入格式。每個小段都是「依題目格式擇一使用」的教學片段,不是要整段全部放進同一份提交程式。Go、Kotlin、VB .NET、C# 等語言片段請放在 `main` / `Sub Main` 裡;需要 `import` / `using` 的語言可參考後方完整範例
讀到 EOF 的完整主程式範例,仍可參考後方「範例程式碼」各語言區塊。這裡額外補充:
- 第一行指定資料筆數 `n`
- 讀到特定條件 `0 0` 結束
- 逗號分隔資料
### PHP 格式片段
```php=
// 第一行指定資料筆數 n
$n = intval(trim(fgets(STDIN)));
for ($i = 0; $i < $n; $i++) {
[$a, $b] = array_map('intval', explode(' ', trim(fgets(STDIN))));
echo ($a + $b) . PHP_EOL;
}
// 讀到 0 0 結束
while (($line = fgets(STDIN)) !== false) {
[$a, $b] = array_map('intval', explode(' ', trim($line)));
if ($a === 0 && $b === 0) break;
echo ($a + $b) . PHP_EOL;
}
// 逗號分隔
$nums = array_map('intval', explode(',', trim(fgets(STDIN))));
echo array_sum($nums) . PHP_EOL;
```
### Rust 格式片段
```rust=
use std::io::{self, Read};
fn main() {
let mut input = String::new();
io::stdin().read_to_string(&mut input).unwrap();
// 第一行指定資料筆數 n
{
let mut it = input.split_whitespace();
let n: usize = it.next().unwrap().parse().unwrap();
for _ in 0..n {
let a: i32 = it.next().unwrap().parse().unwrap();
let b: i32 = it.next().unwrap().parse().unwrap();
println!("{}", a + b);
}
}
// 讀到 0 0 結束
{
let mut it = input.split_whitespace();
while let (Some(a), Some(b)) = (it.next(), it.next()) {
let a: i32 = a.parse().unwrap();
let b: i32 = b.parse().unwrap();
if a == 0 && b == 0 { break; }
println!("{}", a + b);
}
}
// 逗號分隔
let sum: i32 = input.trim().split(',').map(|x| x.parse::<i32>().unwrap()).sum();
println!("{}", sum);
}
```
### Go 格式片段
```go=
// 第一行指定資料筆數 n
var n, a, b int
fmt.Scan(&n)
for i := 0; i < n; i++ {
fmt.Scan(&a, &b)
fmt.Println(a + b)
}
// 讀到 0 0 結束
for {
if _, err := fmt.Scan(&a, &b); err != nil { break }
if a == 0 && b == 0 { break }
fmt.Println(a + b)
}
// 逗號分隔
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
sum := 0
for _, part := range strings.Split(scanner.Text(), ",") {
n, _ := strconv.Atoi(part)
sum += n
}
fmt.Println(sum)
```
### JavaScript 格式片段
```javascript=
// 第一行指定資料筆數 n
const data = require('fs').readFileSync(0, 'utf8').trim().split(/\s+/).map(Number);
let idx = 0;
const n = data[idx++];
for (let i = 0; i < n; i++) {
const a = data[idx++];
const b = data[idx++];
console.log(a + b);
}
// 讀到 0 0 結束
for (let i = 0; i < data.length; i += 2) {
const a = data[i];
const b = data[i + 1];
if (a === 0 && b === 0) break;
console.log(a + b);
}
// 逗號分隔
const nums = require('fs').readFileSync(0, 'utf8').trim().split(',').map(Number);
console.log(nums.reduce((sum, num) => sum + num, 0));
```
### TypeScript 格式片段
```typescript=
declare const require: any;
// 第一行指定資料筆數 n
const data: number[] = require('fs').readFileSync(0, 'utf8').trim().split(/\s+/).map(Number);
let idx = 0;
const n = data[idx++];
for (let i = 0; i < n; i++) {
const a = data[idx++];
const b = data[idx++];
console.log(a + b);
}
// 讀到 0 0 結束
for (let i = 0; i < data.length; i += 2) {
const a = data[i];
const b = data[i + 1];
if (a === 0 && b === 0) break;
console.log(a + b);
}
// 逗號分隔
const nums: number[] = require('fs').readFileSync(0, 'utf8').trim().split(',').map(Number);
console.log(nums.reduce((sum, num) => sum + num, 0));
```
### Kotlin 格式片段
```kotlin=
// 第一行指定資料筆數 n
val n = readLine()!!.trim().toInt()
repeat(n) {
val nums = readLine()!!.trim().split(" ").map { it.toInt() }
println(nums[0] + nums[1])
}
// 讀到 0 0 結束
while (true) {
val nums = readLine()!!.trim().split(" ").map { it.toInt() }
if (nums[0] == 0 && nums[1] == 0) break
println(nums[0] + nums[1])
}
// 逗號分隔
val sum = readLine()!!.split(",").map(String::toInt).sum()
println(sum)
```
### Swift 格式片段
```swift=
// 第一行指定資料筆數 n
let n = Int(readLine()!)!
for _ in 0..<n {
let nums = readLine()!.split(separator: " ").map { Int($0)! }
print(nums[0] + nums[1])
}
// 讀到 0 0 結束
while let line = readLine() {
let nums = line.split(separator: " ").map { Int($0)! }
if nums[0] == 0 && nums[1] == 0 {
break
}
print(nums[0] + nums[1])
}
// 逗號分隔
let sum = readLine()!.split(separator: ",").map { Int($0)! }.reduce(0, +)
print(sum)
```
### VB .NET 格式片段
:::info
以下 VB .NET 片段以 Ubuntu 22.04 的 Mono 測試,套件為 `mono-devel` 與 `mono-vbnc`。`vbnc` 較舊,請避免使用較新的 VB 語法或 LINQ lambda 寫法。
:::
```vbnet=
' 第一行指定資料筆數 n
Dim n As Integer = Integer.Parse(Console.ReadLine())
For i As Integer = 0 To n - 1
Dim parts() As String = Console.ReadLine().Split(" "c)
Dim a As Integer = Integer.Parse(parts(0))
Dim b As Integer = Integer.Parse(parts(1))
Console.WriteLine(a + b)
Next
' 讀到 0 0 結束
Dim line As String = Console.ReadLine()
While line IsNot Nothing
Dim parts() As String = line.Split(" "c)
Dim a As Integer = Integer.Parse(parts(0))
Dim b As Integer = Integer.Parse(parts(1))
If a = 0 AndAlso b = 0 Then Exit While
Console.WriteLine(a + b)
line = Console.ReadLine()
End While
' 逗號分隔
Dim parts() As String = Console.ReadLine().Split(","c)
Dim sum As Integer = 0
For Each part As String In parts
sum += Integer.Parse(part)
Next
Console.WriteLine(sum)
```
### C# 格式片段
:::info
以下 C# 片段以 Ubuntu 22.04 的 Mono `mcs` 測試。
:::
```csharp=
// 第一行指定資料筆數 n
int n = int.Parse(Console.ReadLine());
for (int i = 0; i < n; i++) {
int[] nums = Console.ReadLine().Split().Select(int.Parse).ToArray();
Console.WriteLine(nums[0] + nums[1]);
}
// 讀到 0 0 結束
string line;
while ((line = Console.ReadLine()) != null) {
int[] nums = line.Split().Select(int.Parse).ToArray();
if (nums[0] == 0 && nums[1] == 0) break;
Console.WriteLine(nums[0] + nums[1]);
}
// 逗號分隔
int sum = Console.ReadLine().Split(',').Select(int.Parse).Sum();
Console.WriteLine(sum);
```
### Ruby 格式片段
```ruby=
# 第一行指定資料筆數 n
n = STDIN.gets.to_i
n.times do
a, b = STDIN.gets.split.map(&:to_i)
puts a + b
end
# 讀到 0 0 結束
STDIN.each_line do |line|
a, b = line.split.map(&:to_i)
break if a == 0 && b == 0
puts a + b
end
# 逗號分隔
nums = STDIN.gets.split(',').map(&:to_i)
puts nums.sum
```
## 範例輸入資料
```=
22 1
23 1
24 1
```
## 範例輸出資料
```=
23
24
25
```
---
## 前一版簡單範例程式碼
### Python 程式碼
:::danger
Windows 上 Python會有些功能無法與其他OS產生相同結果
請勿使用字串檔案路徑,請使用例如`os`等內建函式庫
:::
`main.py`
```python=
import sys
for line in sys.stdin.read().splitlines():
# splitlines 會去除不同OS的換行符號
nums = [int(num) for num in line.split()]
# nums = map(int, line.split())
print(sum(nums))
```
`$ python main.py < in.txt`
### Java 程式碼
`Main.java`
```java=
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String input = scanner.nextLine().strip();
String[] nums = input.split(" ");
Integer result = 0;
for(String s: nums) {
result += Integer.parseInt(s);
}
System.out.println(result);
}
scanner.close();
}
}
```
`$ javac Main.java`
`$ java Main < in.txt`
### C 程式碼
`main.c`
```c=
#include<stdio.h>
int main(){
int a, b;
while(!feof(stdin) && scanf("%d %d", &a, &b)){
printf("%d\n", a+b);
}
}
```
`$ gcc main.c -o main`
`$ ./main < in.txt`
### C++ 程式碼
`main.cpp`
```cpp=
#include<iostream>
using namespace std;
int main(){
int a, b;
while(cin >> a >> b){
cout << a + b << endl;
}
}
```
`$ g++ main.cpp -o main`
`$ ./main < in.txt`
### PHP 程式碼
`main.php`
```php=
<?php
$handle = fopen('php://stdin', 'r');
while($line = fgets($handle)){
[$a, $b] = explode(' ', $line);
echo intval($a) + intval($b);
echo PHP_EOL;
}
```
```php=
<?php
$data = explode(PHP_EOL, trim(stream_get_contents(STDIN)));
foreach ($data as $item) {
[$a, $b] = explode(' ', $item);
echo (intval($a) + intval($b)) . PHP_EOL;
}
```
`$ php main.php < in.txt`
### Rust 程式碼
> main.rs
```rust=
use std::io;
use std::io::BufRead;
fn main() {
for line in io::stdin().lock().lines() {
let input = line.unwrap();
let nums: Vec<&str> = input.trim().split(' ').collect();
let result: i32 = nums
.into_iter()
.map(|x| x.parse::<i32>().unwrap())
.sum();
println!("{}", result);
}
}
```
`$ cargo build`
`$ cargo run < in.txt`
### Go 程式碼
```go=
package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
result := 0
numbers := strings.Fields(scanner.Text())
for _, num := range numbers {
n, _ := strconv.Atoi(num)
result += n
}
fmt.Println(result)
}
if scanner.Err() != nil {
log.Fatalln("Scanner Fail.")
}
}
```
### Javascript 程式碼
`main.js`
```javascript=
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', processLine => {
processLine.toString('utf-8').split('\n')
.map(x => x.trim())
.filter(x => !!x)
.map(data => {
console.log(data.split(' ').reduce((x, y) => +x + +y))
})
})
```
`$ node main.js < in.txt`
### Typescript 程式碼
<!-- :::info
- Deno 1.0
:::
```typescript=
const buf = new Uint8Array(1024);
const n = await Deno.stdin.read(buf);
if (n !== null) {
const lines = new TextDecoder().decode(buf.subarray(0, n));
lines.split('\n')
.map(x => x.trim())
.filter(x => !!x)
.map(data => {
console.log(data.split(' ').reduce((x, y) => +x + +y, 0));
})
}
```
`$ deno run main.ts < in.txt` -->
:::info
`$ npm install -g typescript`
> tsc
:::
`main.ts`
```typescript=
declare const process: any;
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', processLine => {
processLine.toString('utf-8').split('\n')
.map(x => x.trim())
.filter(x => !!x)
.map(data => {
console.log(data.split(' ').map(i => +i).reduce((x, y) => x + y))
});
});
```
`$ tsc main.ts --outFile maints.js`
`$ node maints.js < in.txt`
### Kotlin 程式碼
```kotlin=
fun main() {
generateSequence(::readLine)
.map { it.split(" ").map(String::toInt).sum() }
.forEach(::println)
}
```
### Swift 程式碼
```swift=
import Foundation
while let line: String = readLine() {
let result: Int = line.trimmingCharacters(in: .whitespacesAndNewlines)
.split(separator: " ")
.map{Int($0)!}
.reduce(0, +)
print(result)
}
```
`$ swift main.swift < in.txt`
### VB .Net 程式碼
:::info
- Mono VB for Linux
- Ubuntu 22.04 可安裝 `mono-devel` 與 `mono-vbnc`
:::
:::danger
Mono VB compiler `vbnc` 較舊,請避免使用較新的 VB 語法或 LINQ lambda 寫法。
:::
`main.vb`
```vbnet=
Imports System
Module Module1
Sub Main()
While True
Dim Input As String = Console.ReadLine()
If Input Is Nothing Then Exit While
Dim Parts() As String = Input.Split(" "c)
Dim A As Integer = Integer.Parse(Parts(0))
Dim B As Integer = Integer.Parse(Parts(1))
Dim Output As Integer = A + B
Console.WriteLine(Output)
End While
End Sub
End Module
```
```shell=
$ vbnc main.vb -out:main.exe
$ mono main.exe < in.txt
```
### C# 程式碼
:::info
- Mono C# for Linux
:::
`main.cs`
```csharp=
using System;
using System.Linq;
public class Test
{
public static void Main()
{
string line = Console.ReadLine();
while(line != null){
int[] nums = line.Split(' ').Select(x => Int32.Parse(x)).ToArray();
Console.WriteLine(nums[0] + nums[1]);
line = Console.ReadLine();
}
}
}
```
```shell=
$ mcs main.cs -out:main.exe
$ mono main.exe < in.txt
```
### Ruby 程式碼
:::info
- Ruby 2.5
:::
:::danger
Windows 上 Ruby會有些功能無法正常運作
:::
`main.rb`
```ruby=
ARGF.each do |input|
puts input.split.map(&:to_i).sum
end
```
`$ ruby main.rb < in.txt`
參考資料:
> [Online Judge 常見的讀取方式 github jiangsir/PythonBasic](https://github.com/jiangsir/PythonBasic/blob/master/00.%20Online%20Judge%20%E5%B8%B8%E7%94%A8%E8%AE%80%E5%8F%96%E6%96%B9%E5%BC%8F.ipynb)