简体   繁体   中英

Checking user input string

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('\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
    }
}

Thank you for your help.

This is because reader.ReadString returns all the text including the delimiter, so the string returned will be 1\\n 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() .

Thank you ! Here's the "prompt()" code which returns the correct input :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM