พื้นฐาน Go

Reading User Input in Go

Read a line with bufio, trim it and convert it to a number without crashing on bad input.

  • ระดับเริ่มต้น
  • อ่าน 3 นาที
  • ตัวอย่างที่รันได้ 1 ตัวอย่าง
สิ่งที่คุณจะได้เรียนรู้
  • bufio.NewReader
  • strings.TrimSpace
  • strconv.Atoi
From the keyboard to a number
  1. 1ReadString"36\n"
  2. 2TrimSpace"36"
  3. 3strconv.Atoi36, nil
  4. 4age + 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.

ประเด็นสำคัญ

  1. ReadString('\n') reads up to the Enter key.
  2. TrimSpace removes the line ending.
  3. Atoi returns the number and an error.

ตัวอย่าง Go ที่รันได้

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)
}
สร้างปุ่ม Run สำหรับตัวอย่างนี้ ผลลัพธ์จากการรันโค้ด
What is your name?
How old are you?
Hello, Ada! Next year you will be 37.

ฝึกฝน

เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์

เรียนบทนี้จบแล้วใช่ไหม

ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า

ถัดไป: Conditions: if and switch →

ฝึกด้วยโจทย์

ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI

โจทย์ทั้งหมด