0
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.

Golang 標準入力

Last updated at Posted at 2021-06-30

###よくあるパターン① n回ループして各値を受け取る

5
3 1 2 4 5
package main
 
import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)
 
var sc = bufio.NewScanner(os.Stdin) //読み取る準備完了
 
//これを呼ぶたびに入力を受け取る
func nextInt() int {
	sc.Scan()                         //まず読み込む
	ret, _ := strconv.Atoi(sc.Text()) //Textで実際に文字列を読み取る
	return ret
}
 
func main() {
	sc.Split(bufio.ScanWords) //スペース区切りでscanしたい
	n := nextInt()            //n回繰り返すために最初だけ入力を受け取る
	for i := 0; i < n; i++ {
		m := nextInt()	
	}
}

###よくあるパターン②  空白区切りの数値を受け取りたい

0 1000
パターン1

package main
import "fmt"
func main(){
    var A,B float64
    fmt.Scan(&A) //fmt.Scanは空白、改行までを取ってくる
    fmt.Scan(&B)
    fmt.Printf(A,B)
    #=>0 1000
}
パターン2

package main

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

var sc = bufio.NewScanner(os.Stdin)

func nextInt() int {
	sc.Scan()
	ret, _ := strconv.Atoi(sc.Text())
	return ret
}

func main() {
	sc.Split(bufio.ScanWords) //スペースで文字列を区切る
	a := float64(nextInt())
	b := float64(nextInt())

	fmt.Printf(A,B)
        #=>0 1000
}

よくあるパターン③ 一つだけ受け取りたい

180
package main
 
import (
	"fmt"
)
 
func main() {
	var a int
	fmt.Scan(&a)
}

0
0
1

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
0
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?