What`s different between Scan and Scanln

i`m a student who just new to study go. And this is a problem i meet today.


import "fmt"

func main() {
	var key string
	loop := true
	balance := 10000.0
	money := 0.0
	note := ""
	details := "收支\t账户金额\t收支金额\t说明"

	for {
		fmt.Println("\n--------------------家庭收支记账软件-------------------")
		fmt.Println("                  1 details")
		fmt.Println("                  2 input")
		fmt.Println("                  3 withdraw")
		fmt.Println("                  4 exit")
		fmt.Println()
		fmt.Println("               please choice(1-4):")

		fmt.Scanln(&key)

		switch key {
		case "1":
			fmt.Println("--------------------details-------------------")
			fmt.Println(details)
		case "2":
			fmt.Println("input for this time:")
			fmt.Scan(&money)
			fmt.Println("note for this time:")
			fmt.Scan(&note)
			balance += money
			details += fmt.Sprintf("\ninput\t%v\t%v\t%v", balance, money, note)
		case "3":
			fmt.Println("登记支出...")
		case "4":
			loop = false
		default:
			fmt.Println("it`s not right")
		}
		if !loop {
			break
		}

	}
	fmt.Println("you have exit")

}

this is my code .
when it start , i input 2, then input money and note,
then, it start from 2 again ,such as this

but if i use Scanln instead of Scan ( fmt.Scanln(&money) and fmt.Scanln(&note) )it well be ok.
why?
hope some good man can help me

problems is that note variable does not get all the words you typed ?
fmt.Scan stops reading input (stdin) after space.

you probably wanto read whole line (including spaces) to note variable:

2 Likes

Thank you! i have read fmt.package before. but i still do not understand. i just want to input a “3”,no space.

you mean you do not want newline after note ?

you are printing that at the begining of loop, remove it

	for {
                // in Println below do not print newline
		fmt.Println("--------------------家庭收支记账软件-------------------")
		fmt.Println("                  1 details")
		fmt.Println("                  2 input")
		fmt.Println("                  3 withdraw")
		fmt.Println("                  4 exit")
		fmt.Println()
		fmt.Println("               please choice(1-4):")

		fmt.Scanln(&key)

		switch key {
		case "1":
			fmt.Println("--------------------details-------------------")
			fmt.Println(details)
		case "2":
			fmt.Println("money for this time:")
			fmt.Scan(&money)
			fmt.Println("note for this time:")
			fmt.Scanln(&note)
			balance += money
			details += fmt.Sprintf("\ninput\t%f\t%f\t%s", balance, money, note)
			fmt.Printf("note is:" + "'" +note + "'" + "\n")

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.