พื้นฐาน Go
Reading User Input in Go
Read a line with bufio, trim it and convert it to a number without crashing on bad input.
สิ่งที่คุณจะได้เรียนรู้
- bufio.NewReader
- strings.TrimSpace
- strconv.Atoi
From the keyboard to a number
- 1
ReadString"36\n" - 2
TrimSpace"36" - 3
strconv.Atoi36, nil - 4
age + 137
Text in, number out
bufio.NewReader reads from the keyboard one line at a time. The text always arrives as a string, so numbers must be converted with strconv before you calculate with them.
ReadString('\n') returns everything up to the Enter key, and TrimSpace removes the line ending. strconv.Atoi returns the number and an error; the error is not nil when the text is not a number. The sample output uses the answers Ada and 36: in the online compiler, type your answers when the prompts appear.
ประเด็นสำคัญ
ReadString('\n')reads up to the Enter key.- TrimSpace removes the line ending.
- Atoi returns the number and an error.
ตัวอย่าง Go ที่รันได้
main.go
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Println("What is your name?")
name, _ := reader.ReadString('\n')
name = strings.TrimSpace(name)
fmt.Println("How old are you?")
text, _ := reader.ReadString('\n')
age, err := strconv.Atoi(strings.TrimSpace(text))
if err != nil {
fmt.Printf("Hello, %s! That is not a number.\n", name)
return
}
fmt.Printf("Hello, %s! Next year you will be %d.\n", name, age+1)
}
What is your name?
How old are you?
Hello, Ada! Next year you will be 37.ฝึกฝน
เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์
เรียนบทนี้จบแล้วใช่ไหม
ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า
ความคืบหน้าของคุณถูกบันทึกไว้ในเบราว์เซอร์นี้ เข้าสู่ระบบเพื่อเก็บไว้ใช้ได้ทุกอุปกรณ์
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
- รวมเฉพาะตัวเลขที่ถูกต้อง บวกค่าที่เป็นจำนวนเต็มและข้ามอย่างอื่นไป เหมือนที่ try/except จัดการอินพุตที่ไม่ถูกต้อง. ง่าย
- Absolute Value Without abs Compute an absolute value with a condition. ง่าย