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 खराब input को संभालता है. आसान
- Absolute Value Without abs Compute an absolute value with a condition. आसान