0
0

More than 3 years have passed since last update.

コマンドラインから文字列の取得

Posted at

初めに

Atcoderの文字列取得の定石を貼ります。

コマンドラインから複数行一度に取得

package main

import(
   "fmt"
   "bufio"
   "stdin"
)

func main(){
  lines := getStdin()
  for k,v := range lines{
    fmt.Printf("line[%s]=%s\n",k,v)
  }

}

func getStdin() []string {
    stdin := bufio.NewScanner(os.Stdin)
    lines := []string{}
    for stdin.Scan() {
        if err := stdin.Err(); err != nil {
            fmt.Fprintln(os.Stderr, err)
        }
        lines = append(lines, stdin.Text())
    }
    return lines
}

実行結果

$go run sample.go
a b c d e//コマンドライン入力
f g h i j//コマンドライン入力
line[0]="a b c d e"//出力
line[1]="f g h i j"//出力

コマンドラインから得た文字列を空白区切りで返す(string型)

func splitspace(line string) []string {
    words := strings.Split(line, " ")
    return words
}

コマンドラインから得た文字列を空白区切りで返す(int型)

func splitspace(line string) []int {
    buf := strings.Split(line, " ")
    num := stringToInt(buf)
    return t
}

func stringToInt(i []string) []int {
    f := make([]int, len(i))
    for n := range i {
        f[n], _ = strconv.Atoi(i[n])
    }
    return f
}
0
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
0
0