How do I check if the user has entered a null value in Go?

huangapple go评论96阅读模式
英文:

How do I check if the user has entered a null value in Go?

问题

以下是翻译好的内容:

reader := bufio.NewReader(os.Stdin)
fmt.Print("输入文本:")
text, _ := reader.ReadString('\n')
fmt.Println("你好", text)

我该如何检查用户是否输入了空值,代码应该放在哪里?注意 - 我已经尝试过检查长度= 0= "",但它们似乎不起作用。

请提供另一种方法。谢谢!

英文:
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter text: ")
text, _ := reader.ReadString('\n')
fmt.Println("Hello",text)

How do I check if the user has entered a null value and where do I put the code? Note - I've already tried checking the length = 0 and = " " but, they don't seem to be working.

Please suggest an alternative way for doing this. Thanks!

答案1

得分: 6

bufio.Reader.ReadString() 返回一个包含分隔符的字符串,对于换行符\n来说也是如此。

如果用户没有输入任何内容,只是按下了<kbd>Enter</kbd>键,ReadString() 的返回值将是 "\n",因此你需要将结果与 "\n" 进行比较以检查空输入:

reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter text: ")
text, err := reader.ReadString('\n')
if err != nil {
    panic(err) // 不要忘记检查和处理返回的错误!
}

if text == "\n" {
    fmt.Println("No input!")
} else {
    fmt.Println("Hello", text)
}

更好的替代方法是使用 strings.TrimSpace(),它会删除前导和尾随的空白字符(包括换行符;如果有人输入两个空格然后按下<kbd>Enter</kbd>键,这个解决方案也会过滤掉)。如果在调用 strings.TrimSpace() 之前将其与空字符串 "" 进行比较:

text = strings.TrimSpace(text)
if text == "" {
    fmt.Println("No input!")
} else {
    fmt.Println("Hello", text)
}
英文:

bufio.Reader.ReadString() returns a string that also contains the delimeter, in this case the newline character \n.

If the user does not enter anything just presses the <kbd>Enter</kbd> key, the return value of ReadString() will be &quot;\n&quot;, so you have to compare the result to &quot;\n&quot; to check for empty input:

reader := bufio.NewReader(os.Stdin)
fmt.Print(&quot;Enter text: &quot;)
text, err := reader.ReadString(&#39;\n&#39;)
if err != nil {
	panic(err) // Don&#39;t forget to check and handle returned errors!
}

if text == &quot;\n&quot; {
	fmt.Println(&quot;No input!&quot;)
} else {
	fmt.Println(&quot;Hello&quot;, text)
}

An even better alternative would be to use strings.TrimSpace() which removes leading and trailing white space characters (newline included; it isn't a meaningful name if someone inputs 2 spaces and presses <kbd>Enter</kbd>, this solution also filters that out). You can compare to the empty string &quot;&quot; if you called strings.TrimSpace() prior:

text = strings.TrimSpace(text)
if text == &quot;&quot; {
	fmt.Println(&quot;No input!&quot;)
} else {
	fmt.Println(&quot;Hello&quot;, text)
}

答案2

得分: 0

// 我迄今为止编写的最好的算法

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	欢迎()
	sina := 获取信息()
	fmt.Printf("%v", sina)
	再见()
}

func 欢迎() {
	fmt.Println("欢迎来到这个程序...[*]")
}

func 获取信息() string {
	reader := bufio.NewReader(os.Stdin)
	fmt.Print("输入名字: ")
	firstName, _ := reader.ReadString('\n')
	if len(firstName) >= 5 {
		return firstName
	}
	for {
		fmt.Print("名字必须超过3个字符: ")
		firstName, _ := reader.ReadString('\n')
		if len(firstName) < 5 {
			continue
		} else if len(firstName) >= 5 {
			return firstName
		}
	}
}

func 再见() {
	fmt.Println("   ")
	fmt.Println("   ")
	fmt.Println(" [*]----------------------[*]  ")
	fmt.Println(" [*]----谢谢再见----[*]  ")
	fmt.Println(" [*]----------------------[*]  ")
	fmt.Println("   ")
	fmt.Println("   ")
}

请注意,我只翻译了代码部分,其他内容不做翻译。

英文:

// The best algorithm I have written so far

package main

import (
	&quot;bufio&quot;
	&quot;fmt&quot;
	&quot;os&quot;
)

func main() {
	Wellcome()
	sina := get_Informations()
	fmt.Printf(&quot;%v&quot;, sina)
	Goodbye()
}

func Wellcome() {
	fmt.Println(&quot;Welcome to this Program ...[*]&quot;)
}

func get_Informations() (string){
	reader := bufio.NewReader(os.Stdin)
	fmt.Print(&quot;Enter First-Name: &quot;)
	firstName, _ := reader.ReadString(&#39;\n&#39;)	
	if len(firstName) &gt;= 5 {
		return firstName
	}
	for {
		fmt.Print(&quot;First-Name must be more than 3 characters: &quot;)	
		firstName, _ := reader.ReadString(&#39;\n&#39;)	
		if len(firstName) &lt; 5 {
			continue
		}else if len(firstName) &gt;=5{
			return firstName
		} 

	}
}

func Goodbye() {
	fmt.Println(&quot;   &quot;)
	fmt.Println(&quot;   &quot;)
	fmt.Println(&quot; [*]----------------------[*]  &quot;)
	fmt.Println(&quot; [*]----THANKS.GOODBYE----[*]  &quot;)
	fmt.Println(&quot; [*]----------------------[*]  &quot;)
	fmt.Println(&quot;   &quot;)
	fmt.Println(&quot;   &quot;)
}

huangapple
  • 本文由 发表于 2017年4月19日 16:16:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/43490148.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定