Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read lines from stdin until certain character

Tags:

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 ?

like image 975
astropanic Avatar asked Jan 07 '13 22:01

astropanic


1 Answers

... is ReadString messing with my data?

No, it isn't. It is reading up to the next '\n'. That means that a line with only a dot on it will have the data ".\n" or ".\r\n" depending on the operating system.

To remove line endings, I would do input = strings.TrimRight(input, "\r\n")

like image 104
Stephen Weinberg Avatar answered Oct 20 '22 22:10

Stephen Weinberg