dongyue9860 2017-01-21 18:45 采纳率: 100%
浏览 32
已采纳

检查用户输入字符串

I am new in GoLang and I am encountering a problem with this condition: Even if the input of the user is "1", it doesn't enter in the if statement.

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('
');
    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
    }
}

Thank you for your help.

  • 写回答

2条回答 默认 最新

  • duanlinghe8417 2017-01-21 18:50
    关注

    This is because reader.ReadString returns all the text including the delimiter, so the string returned will be 1 not just 1. From the documentation (my emphasis):

    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.

    Perhaps you want to do

    return strings.TrimSpace(text)
    

    at the end of prompt().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 这个复选框什么作用?
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下