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 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?