owned this note
owned this note
Published
Linked with GitHub
---
title: 程式輸入輸出範例
tags: code, vb.net, python, ruby, java
---
# StdIn 範例
## 範例輸入資料
```=
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
- VB .Net 2010 (Mono VB for Linux)
:::
:::danger
Mono VB 函式庫需要額外Import
即VB寫法會與visual studio有些差異
> 例如:ArrayList
> 必須用 Imports System.Collections
:::
`main.vb`
```=
Module Module1
Sub Main()
While True
Dim Input As String = Console.ReadLine()
If Input Is Nothing Then Exit While
Dim Data() As Integer = Input.Split(" ").Select(Function(x) CInt(x)).ToArray
Dim A As Integer = Data(0)
Dim B As Integer = Data(1)
Dim Output As Integer = A + B
Console.WriteLine(Output)
End While
End Sub
End Module
```
`$ vbc main.vb` 編譯程式碼
`$ main < in.txt` for windows
`$ mono main.exe < in.txt` for mono
```shell=
$ vbc 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();
}
}
}
```
`$ csc main.cs`
`$ ./main < in.txt`
```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`