// Redo this one! // // Please enter path to name file: // /home/toor/names.txt // Printing scanned names: // Drew Bednar // Margot Robbie // Sean Carey // Exiting... // toor@toor-jammy-jellifish:~/tmp$ cat read.go // package main // import ( // "fmt" // "os" // "bufio" // "strings" // ) // type Person struct { // fname string // lname string // } // func main (){ // fmt.Println("Please enter path to name file:") // reader := bufio.NewReader(os.Stdin) // inputBytes, _, _ := reader.ReadLine() // path := string(inputBytes) // file, err := os.Open(path) // if err != nil { // fmt.Println("Error: ", err) // } else { // slice := make([]Person, 0) // scanner := bufio.NewScanner(file) // for scanner.Scan() { // line := scanner.Text() // sarr := strings.Split(line, " ") // slice = append(slice, Person{sarr[0], sarr[1]}) // } // if err := scanner.Err(); err != nil { // fmt.Println("Error: ", err) // } // file.Close() // fmt.Println("Printing scanned names:") // for _, p := range slice { // fmt.Println(p.fname, " ", p.lname) // } // } // fmt.Println("\nExiting...") // } // package main import ( "fmt" "os" "strings" ) type Person struct { Fname string Lname string } func parseName(name string) Person { names := strings.Split(name, " ") p := Person{Fname: names[0], Lname: strings.TrimSpace(names[1])} return p } func main() { var filePath string var people []Person fmt.Println("Please provide the path to a text file of first and last names:") _, err := fmt.Scan(&filePath) if err != nil { fmt.Fprintf(os.Stderr, "Error. Something when wrong with the path you provided.") os.Exit(1) } data, err := os.ReadFile(filePath) if err != nil { fmt.Fprintf(os.Stderr, "Error. Something when wrong with the path you provided.") os.Exit(1) } file_lines := strings.Split(string(data), "\n") for _, v := range file_lines { if len(strings.Split(v, " ")) == 2 { people = append(people, parseName(v)) } } for _, v := range people { fmt.Printf("First Name: %s, Last Name: %s\n", v.Fname, v.Lname) } }