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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With