Skip to content

Instantly share code, notes, and snippets.

@Ozoniuss
Created September 30, 2023 11:20
Show Gist options
  • Save Ozoniuss/e9b13a388c9136a3f8ad803a074d3f64 to your computer and use it in GitHub Desktop.
Save Ozoniuss/e9b13a388c9136a3f8ad803a074d3f64 to your computer and use it in GitHub Desktop.
1-prompter, first attempt
package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
// scanStringUntilValid is a helper provided to get a string input from the
// terminal. It doesn't do any additional logic to simply retrieving the user
// input; it is only provided for consistency.
func scanStringUntilValid(s *bufio.Scanner, prefix string) string {
fmt.Print(prefix)
s.Scan()
return s.Text()
}
// scanIntUntilValid is a helper provided to get a float input from the terminal.
// It will prompt the user for a value until the value is a valid floating
// point number.
func scanFloatUntilValid(s *bufio.Scanner, prefix string) float64 {
var valfloat float64
var err error
for {
fmt.Print(prefix)
s.Scan()
val := s.Text()
if valfloat, err = strconv.ParseFloat(val, 64); err != nil {
fmt.Println("Invalid number, please try again.")
continue
}
return float64(valfloat)
}
}
type Debt struct {
Person string
Amount float64
Currency string
Details string
}
func CreateDebtPrompter(header string) Debt {
if header != "" {
fmt.Println(header)
}
s := bufio.NewScanner(os.Stdin)
debt := Debt{}
debt.Person = scanStringUntilValid(s, "person: ")
debt.Amount = scanFloatUntilValid(s, "amount: ")
debt.Currency = scanStringUntilValid(s, "currency: ")
debt.Details = scanStringUntilValid(s, "details: ")
return debt
}
func main() {
debt := CreateDebtPrompter("")
fmt.Println("debt created: %s", debt)
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment