1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[競プロ]Goの標準入力をまとめる

Last updated at Posted at 2020-11-25

##はじめに
ある日Paizaにハマったので、Goの標準入力についてまとめておく。
##1つのデータの入力

package main

import "fmt"

func main() {
	var s string
	fmt.Scan(&s)
	fmt.Println(s)
}

##1行のデータの入力

package main

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

func main()  {
	reader := bufio.NewReader(os.Stdin)
	s, _ := reader.ReadString('\n')
	fmt.Println(s)
}

##n行のデータの入力(1行目にデータ数)

package main

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

func main()  {
	reader := bufio.NewReader(os.Stdin)
	s, _ := reader.ReadString('\n')
	s = strings.TrimSpace(s)
	n, _ := strconv.Atoi(s)
	for i:=0; i<n; i++ {
		s, _ = reader.ReadString('\n')
		s = strings.TrimSpace(s)
		fmt.Println(s)
	}
}

##複数のデータ(今回は3つ)の入力(スペース区切り)

package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func main() {
	reader := bufio.NewReader(os.Stdin)
	s, _ := reader.ReadString('\n')
	s = strings.TrimSpace(s)
	t := strings.Split(s, " ")
	fmt.Println(t[0])
	fmt.Println(t[1])
	fmt.Println(t[2])
}

##n個のデータの入力(1行目にデータ数, 2行目にn個のデータ(スペース区切り))


package main

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

func main()  {
	reader := bufio.NewReader(os.Stdin)
	s, _ := reader.ReadString('\n')
	s = strings.TrimSpace(s)
	n, _ := strconv.Atoi(s)

	s, _ = reader.ReadString('\n')
	s = strings.TrimSpace(s)
	t := strings.Split(s, " ")

	for i:=0; i<n; i++ {
		fmt.Println(t[i])
	}
}

##行列の作成

package main

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

func main() {
	var matrix[][] string
	reader := bufio.NewReader(os.Stdin)
	s, _ := reader.ReadString('\n')
	s = strings.TrimSpace(s)
	t := strings.Split(s, " ")
	n, _ := strconv.Atoi(t[0])

	for i:=0; i<n; i++ {
		s, _ = reader.ReadString('\n')
		s = strings.TrimSpace(s)
		x := strings.Split(s, "")
		matrix = append(matrix, x)
	}
	fmt.Println(matrix)
}
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?