gpt4 book ai didi

go - 检查用户输入的字符串

转载 作者:IT王子 更新时间:2023-10-29 02:29:24 25 4
gpt4 key购买 nike

我是 GoLang 的新手,我遇到了这种情况的问题:即使用户输入的是“1”,也不会进入if语句。

package main

import (
"bufio"
"fmt"
"os"
"strconv"
"math"
"strings"
)

func prompt(toprint string) string{
if(toprint == ""){
toprint = "Enter text :";
}
reader := bufio.NewReader(os.Stdin);
fmt.Println(toprint);
text, _ := reader.ReadString('\n');
return text;
}

func main() {
choice := prompt("Please enter '1'");

if(strings.Compare("1",choice)==0||choice=="1"){
// D'ONT ENTER HERE EVEN WHEN choice=="1"
}else{
// Always go here
}
}

感谢您的帮助。

最佳答案

这是因为 reader.ReadString 返回包括分隔符在内的所有文本,所以返回的字符串将是 1\n 而不仅仅是 1 .来自 the documentation (我的重点):

func (*Reader) ReadString

func (b *Reader) ReadString(delim byte) (string, error)

ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter. If ReadString encounters an error before finding a delimiter, it returns the data read before the error and the error itself (often io.EOF). ReadString returns err != nil if and only if the returned data does not end in delim. For simple uses, a Scanner may be more convenient.

也许你想做

return strings.TrimSpace(text)

prompt() 的末尾。

关于go - 检查用户输入的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41783108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com