我一直在寻找一种如何在C
中使用这样的语法的方法scanf("%d",&num);
我在Go Lanuguage中发现你可以使用这个
fmt.scanf("%d",&num)
问题是当我两次使用它时,它不允许我在第二部分输入值。
示例:
package main
import "fmt"
func main() {
var name string
var age int
fmt.Print("Enter your name: ")
fmt.Scanf("%s", &name)
fmt.Print("\nEnter your age: ")
fmt.Scanf("%d", &age)
fmt.Println(name,"is",age,"years of Age")
}
示例输入名称=杰克和年龄= 18(这是问题的一部分,它不允许我输入年龄) 它会显示
Jack is 0 years of age
答案 0 :(得分:1)
您可以用以下内容替换最后一行:
fmt.Printf("%s is %d years of age", name, age)
以下是完整代码:
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("\n%s is %d years of age \n", name, age)
}
输出:
输入您的姓名:rex
输入您的年龄:33
雷克斯已经33岁了
答案 1 :(得分:1)
试试这个:
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
r := bufio.NewReader(os.Stdin)
fmt.Print("Enter your name: ")
name, _ := r.ReadString('\n')
fmt.Print("Enter your age: ")
age, _ := r.ReadString('\n')
name, age = strings.TrimSpace(name), strings.TrimSpace(age) //remove \n
fmt.Println(name, "is", age, "years of Age")
}