I've been looking for a way how to have a syntax like this in C
scanf("%d",&num);
and I've found out in Go Lanuguage you can use this
fmt.scanf("%d",&num)
The problem is when I'll use it twice, it doesn't allow me to enter a value on the second part.
Example:
package main
import "fmt"
func main() {
var name string
var age int
fmt.Print("Enter your name: ")
fmt.Scanf("%s", &name)
fmt.Print("
Enter your age: ")
fmt.Scanf("%d", &age)
fmt.Println(name,"is",age,"years of Age")
}
Sample input name=Jack and age=18(this is the part of the problem wherein it doesn't allow me to input for the age) it will display
Jack is 0 years of age
You can replace the last line with this:
fmt.Printf("%s is %d years of age", name, age)
Here is the full code:
package main
import "fmt"
func main() {
var name string
var age int
fmt.Print("Enter your name: ")
fmt.Scanf("%s", &name)
fmt.Print("Enter your age: ")
fmt.Scanf("%d", &age)
fmt.Printf("
%s is %d years of age
", name, age)
}
Output :
Enter your name: rex
Enter your age: 33
rex is 33 years of age
Try this:
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
r := bufio.NewReader(os.Stdin)
fmt.Print("Enter your name: ")
name, _ := r.ReadString('
')
fmt.Print("Enter your age: ")
age, _ := r.ReadString('
')
name, age = strings.TrimSpace(name), strings.TrimSpace(age) //remove
fmt.Println(name, "is", age, "years of Age")
}