LoginSignup
6
8

More than 3 years have passed since last update.

競プロで使うための GO 入門 ~標準入出力~

Last updated at Posted at 2020-07-23

Index

標準入出力

標準入出力は、"fmt"パッケージをインポートする。

package main

import (
    "fmt" // fmtパッケージ
)

func main() {

}

標準入力(Standard Input)

fmt.Scan()

  • 改行またはスペースまでの文字列を取得する。
    // 入力に123と書く

    var d int
    fmt.Scan(%d)

    fmt.Println(d) // ->123

高速で読み込み(bufio.NewScanner(os.Stdin))

高速で大量に読み込む必要がある場合

package main

import (
    "bufio"
    "fmt"
    "os"
    "strconv"
)

var sc = bufio.NewScanner(os.Stdin)

// 文字列を読み込み戻り値をintで返す
func nextInt() int {
    sc.Scan()
    ret, e := strconv.Atoi(sc.Text())
    if e != nil {
        panic(e)
    }
    return ret
}

// メイン
func main() {
    // スペースで文字列を区切る
    sc.Split(bufio.ScanWords)

    // 入力例
    // 5
    // 1 2 3 4 5

    n := nextInt()
    fmt.Println(n)
    for i := 0; i < n; i++ {
        m := nextInt()
        fmt.Printf("%d ", m) // ->1 2 3 4 5
    }
}

標準出力(Standard Output)

fmt.Println()

  • 引数を改行付きで出力する
  • 引数が複数の場合は、スペースが入る
    // 数値
    fmt.Println(123) // ->123

    fmt.Println(123, 456) // ->123 456

    // 文字列
    fmt.Println("abc") // ->abc

    fmt.Println("abc", "def") // ->abc def

    // 数値, 文字列
    fmt.Println(123, "abc") // ->123 abc

fmt.Printf()

  • フォーマットを指定して出力する
  • 第1引数にフォーマットを指定しないこともできる
  • 第2引数にスペースは含まれない
    var d int = 123

    // %d数値指定
    fmt.Printf("%d\n", d) // ->123

    // %s文字列指定(エラーにならないが出力で指摘される)
    fmt.Printf("%s\n", d) // ->%!s(int=123)

    // %v汎用
    fmt.Printf("%v\n", d) // ->123


    var s string = "abc"

    // 文字列指定
    fmt.Printf("%s\n", s) // ->abc

    // %d数値指定(エラーにならないが出力で指摘される)
    fmt.Printf("%d\n", s) // ->%!d(string=abc)

    // %v汎用
    fmt.Printf("%v\n", s) // ->abc

    // %#vダブルクウォート付加(文字列であればダブルクウォートが付加される)
    fmt.Printf("%#v\n", s) // ->"abc"
6
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
8