dsgdfg30210 2019-09-17 15:00
浏览 636

在Golang中通过fmt.Scanln()接受用户输入时出现问题

I m trying to take an input from the user through my console in golang by using fmt.Scanln(). It is working fine under normal circumstances. However, whenever I take input in a loop, the inputs are correct in the first iteration but during the next iterations of a loop, an extra smiley is added in the front of the received string. I don't know what the problem is. Will be very thankful if anyone proposes some solution.

func (a *Block) fillBlock() {
fmt.Println("Block Details:")
fmt.Print("Enter Block Name: ")
fmt.Scanln(&a.Data)

for i := 0; i < Students; i++ {
    fmt.Print(i, "Enter Student Roll# ")
    fmt.Scanln(&a.Grades[i].Rollno)
    fmt.Print(i, "Enter Student Grade# ")
    fmt.Scanln(&a.Grades[i].Grade)
}

fmt.Println("
Input Data:")

fmt.Println("Data: ",a.Data)

// Iterating over each student
for i := 0; i < Students && (a.Grades[i].Rollno != "" && a.Grades[i].Grade != ""); i++ {
    fmt.Println("Rollno: " + string(i) + a.Grades[i].Rollno)
    fmt.Println("Grade: " + string(i) + a.Grades[i].Grade)
}

}

Output

  • 写回答

1条回答 默认 最新

  • douyou9923 2019-09-17 15:07
    关注

    This is wrong:

        fmt.Println("Rollno: " + string(i) + a.Grades[i].Rollno)
    

    Instead, use

        fmt.Println("Rollno: " + strconv.Itoa(i) + a.Grades[i].Rollno)
    

    Or, better:

        fmt.Printf("Rollno: %d %s
    ",i a.Grades[i].Rollno)
    
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!