dtv55860 2016-08-13 13:34
浏览 56
已采纳

将字符串数组的单个元素初始化为Go lang中的另一个字符串变量

In this code, I read a text file for input (A1,B2) and Im using the split function to separate them at comma and store in strs, according to the function definition its returns a array in this case it is strs array, i want the first element in strs to be in currentSource and the second element to be in CurrentDest.I tried printing both the variables individually to check if its working,but the program exits after that and I get a error saying Panic: index out of range. Can anybody help me out..!!!

var currentSource string
var currentDest string

func main() {

    file, err := os.Open("chessin.txt")
    if err != nil {
        fmt.Println(err)
    }
    defer file.Close()
    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        strs := strings.Split(scanner.Text(), ",")

        currentSource = strs[0]
        currentDest = strs[1]
}
  • 写回答

2条回答 默认 最新

  • dongtong848825 2016-08-13 13:52
    关注

    This works

    var currentSource string
    var currentDest string
    
    func main() {
    
        file := "A1,B2
    "
        scanner := bufio.NewScanner(strings.NewReader(file))
        for scanner.Scan() {
            strs := strings.Split(scanner.Text(), ",")
    
            currentSource = strs[0]
            currentDest = strs[1]
    
            fmt.Println(strs)
        }
    
    
    }
    

    Are you sure your file (chessin.txt) it is ok?

    Playground

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 TCP的客户端和服务器的互联
  • ¥15 VB.NET操作免驱摄像头
  • ¥15 笔记本上移动热点开关状态查询
  • ¥85 类鸟群Boids——仿真鸟群避障的相关问题
  • ¥15 CFEDEM自带算例错误,如何解决?
  • ¥15 有没有会使用flac3d软件的家人
  • ¥20 360摄像头无法解绑使用,请教解绑当前账号绑定问题,
  • ¥15 docker实践项目
  • ¥15 利用pthon计算薄膜结构的光导纳
  • ¥15 海康hlss视频流怎么播放