This is a small snippet of code supposed to read a list of space-separated values of first name and last name from a text file and put the result into a slice in Go. For some reason, only the first item is stored in the slice:
package main
import (
"fmt"
"bufio"
"os"
//"io"
//"strings"
)
type Person struct {
fName string
lName string
}
func main() {
// a scanner to read input with spaces
scanner := bufio.NewScanner(os.Stdin)
fmt.Print("Enter a file name: ")
scanner.Scan()
fileName := scanner.Text()
scanner = nil //close this scanner
file, err := os.Open(fileName)
if err != nil {
fmt.Fprintf(os.Stderr, "os.Open error: %v\n", err)
return
}
fmt.Println() //empty string
fileScanner := bufio.NewScanner(file)
fileScanner.Split(bufio.ScanLines)
var persons []Person = make([]Person, 0, 3)
for fileScanner.Scan() {
line := fileScanner.Text()
fmt.Println(line)
var (
firstName string
lastName string
)
fmt.Sscanln(line, &firstName, &lastName)
person := Person{truncateString(firstName, 20), truncateString(lastName, 20)}
persons = append(persons, person)
}
file.Close()
fmt.Println("Items: ", len(persons))
for i, element := range persons {
fmt.Printf("%v %s %s\n", i, element.fName, element.lName)
}
}
func truncateString(input string, length int) string {
if len(input) > length {
return string(input[0:length])
} else {
return input
}
}
To debug it I added an fmt.Println() to print out the lines of the input file. Surprisingly, it does not print the strings on new lines, but rather, as far as I can judge from the output, it overwrites the strings over the same line.
For the input file:
Harper Collins
Billy Bons
John Bon Jovi
It gives the output:
Enter a file name: names.txt
John Bon Jovis
1
0 Harper Collins
The last s is obviously from a longer name overwritten.
What can be the reason?