Monday, 13 May 2019

Go language: Read input from console


Approach 1: Using bufio.NewScanner

func readData(message string) string {
    fmt.Println(message)
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Scan()

    if scanner.Err() != nil {
        return "Can't read input"
    }

    return scanner.Text()
}

App.go
package main

import (
    "bufio"
    "fmt"
    "os"
)

func readData(message string) string {
    fmt.Println(message)
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Scan()

    if scanner.Err() != nil {
        return "Can't read input"
    }

    return scanner.Text()
}

func main() {
    userName := readData("Enter your name")
    city := readData("Enter your city")
    country := readData("Enter your country")

    fmt.Println("\nUser Entered\n")
    fmt.Println("User Name : ", userName)
    fmt.Println("City : ", city)
    fmt.Println("Country : ", country)
}

Output
Enter your name
Krishna
Enter your city
Bangalore
Enter your country
India

User Entered

User Name :  Krishna
City :  Bangalore
Country :  India

Approach 2: Using fmt.Scanln
var data string
fmt.Scanln(&data)


App.go
package main

import (
    "fmt"
)

func readData(message string) string {
    fmt.Println(message)
    var data string
    fmt.Scanln(&data)

    return data
}

func main() {
    userName := readData("Enter your name")
    city := readData("Enter your city")
    country := readData("Enter your country")

    fmt.Println("\nUser Entered\n")
    fmt.Println("User Name : ", userName)
    fmt.Println("City : ", city)
    fmt.Println("Country : ", country)
}

Output
Enter your name
Krishna
Enter your city
Bangalore
Enter your country
India

User Entered

User Name :  Krishna
City :  Bangalore
Country :  India

Approach 3: Using fmt.Scanf
var data string
fmt.Scanf("%s", &data)


App.go
package main

import (
    "fmt"
)

func readData(message string) string {
    fmt.Println(message)
    var data string
    fmt.Scanf("%s", &data)

    return data
}

func main() {
    userName := readData("Enter your name")
    city := readData("Enter your city")
    country := readData("Enter your country")

    fmt.Println("\nUser Entered\n")
    fmt.Println("User Name : ", userName)
    fmt.Println("City : ", city)
    fmt.Println("Country : ", country)
}




Previous                                                 Next                                                 Home

No comments:

Post a Comment