54
51

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 5 years have passed since last update.

[Go] ファイルや標準入力から一行ずつ読み込む

Posted at

おあつらえ向きな関数名のbufio.ReadLine()というのがありました。が、ドキュメントを読むとこれは低レベルの関数で、たいていの利用者はReadBytes('\n')かReadString('\n')かScannerを使うべきとあります。

bufio.Scannerを使うのが良いようです。Example (Lines)のところにそのものスバリのサンプルコードがあります。

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		fmt.Println(scanner.Text()) // Println will add back the final '\n'
	}
	if err := scanner.Err(); err != nil {
		fmt.Fprintln(os.Stderr, "reading standard input:", err)
	}
}

空白区切りで単語単位で読み込む例も書いてあります。

54
51
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
54
51

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?