Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang for loop wont stop

Tags:

go

So I am starting to learn the Go Programming Language and was hoping someone might be able to clarify why I'm getting the results I'm getting. I'm trying to have the program read input from the user and display it back until the user only enters the newline character. package main

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

func main(){

    inputBuff := bufio.NewReader(os.Stdin)
    line,_ := inputBuff.ReadString('\n')

    for  (!strings.EqualFold(line,"\n")){
        line,err := inputBuff.ReadString('\n')
        if err!=nil {
            fmt.Println(err)
        }
        fmt.Println(line)
        fmt.Println(!strings.EqualFold(line,"\n"))
    }

}

I am trying to read in full strings at a time so i thought the bufio would be better the using Scan. I added the last print to show that the method is returning false but the loop continues to execute. Any help would be greatly appreciated.

like image 239
165plo Avatar asked Jan 12 '23 07:01

165plo


1 Answers

the line inside the loop is not the same line you initiated for the check. FTFY:

package main

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

func main(){

    inputBuff := bufio.NewReader(os.Stdin)
    line,_ := inputBuff.ReadString('\n')
    var err error
    for  (!strings.EqualFold(line,"\n")){
        line,err = inputBuff.ReadString('\n')
        if err!=nil {
            fmt.Println(err)
        }
        fmt.Println(line)
        fmt.Println(!strings.EqualFold(line,"\n"))
    }

You used the := assignment operator inside the loop, as in line, err := ..... This makes Go create a new symbol inside the the for loop with the name line. But the for's check is outside the inner scope of the loop code block. So it refers to the old line that was initiated outside the loop.

Changing the operator inside the loop to = doesn't create a new variable, but also doesn't init err, so I defined it beforehand too. err can be declared inside the loop but that's redundant.

like image 61
Not_a_Golfer Avatar answered Jan 30 '23 18:01

Not_a_Golfer