Go – Read lines from stdin until certain character

go

I'm learning Go.

My program should read data from stdin until I enter a line with a single period.

package main

import (

  "os"
  "fmt"
  "bufio"

)

func main(){

  in    := bufio.NewReader(os.Stdin)
  input := ""

  for input != "." {
    input, err := in.ReadString('\n')
    if err != nil {
      panic(err)
    }
  }
}

How I should modify my for loop, to stop the program when I enter a single dot ?

I tried to implement a while loop with the for statement, is there something wrong with my approach, is the condition wrong, or is ReadString messing with my data ?

Best Answer

Just in case anybody else comes across this question:

Since Go 1.1 there's a much nicer way of looping over the lines of some input available. This is how I would tackle OP's problem today:

package main

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

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    for scanner.Scan() {
        line := scanner.Text()
        if line == "." {
            break
        }
        fmt.Println(line) // or do something else with line
    }
}

scanner.Text() automatically strips the trailing newline.

Related Topic