When i try to input name from keyboard it is not taking the input

72 views
Skip to first unread message

Sagar Byahatti

unread,
Feb 20, 2024, 8:22:50 AM2/20/24
to golang-nuts
package main

import "fmt"

func main() {

    var projectName = "APY"
    var sub = 50

    fmt.Println("Welcome to", projectName, " the number of subscriber is ", sub)
    fmt.Println("Enter your name: ")
    var userName string

    fmt.Scan(&userName)

    fmt.Printf("%v, your PRAN Number is", userName)

}

Marvin Renich

unread,
Feb 20, 2024, 10:52:15 AM2/20/24
to golan...@googlegroups.com
* Sagar Byahatti <sagarb...@gmail.com> [240220 08:22]:
fmt.Scan is probably not what you want, though if I run your program and
type a single word (no spaces) and then a newline, I get the result that
I think you are expecting.

You probably want to look at the bufio package, and specifically the
Reader.ReadString method. Something like (untested)

var input = bufio.NewReader(os.Stdin)
var userName, err = input.ReadString('\n')

...Marvin

Marvin Renich

unread,
Feb 20, 2024, 11:12:25 AM2/20/24
to golan...@googlegroups.com
* Marvin Renich <mr...@renich.org> [240220 10:52]:
Then use strings.TrimSpace on userName to get rid of the trailing '\n'
and any other leading or trailing blanks:

userName = strings.TrimSpace(userName)

Don't forget to check err for non-nil and handle the error accordingly.

...Marvin

Reply all
Reply to author
Forward
0 new messages