2016-08-13 78 views
0

在此代码中,我读取了用于输入(A1,B2)和Im的文本文件,并使用split函数以逗号分隔它们并以strs存储,函数定义它返回一个数组,在这种情况下它是strs数组,我想strs中的第一个元素在currentSource中,第二个元素在CurrentDest中。我尝试单独打印两个变量来检查它是否工作,但是程序退出后,我得到一个错误说Panic:索引超出范围。 有人可以帮我解决.. !!!初始化字符串数组中的单个元素为Go中的另一个字符串变量lang

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] 
} 
+0

您应该标记您的语言。 :) –

+0

'strings.Split'不会返回一个数组,而是一串字符串。而且你必须真正检查'len(strs)> = 2'。文件的内容是什么? –

+0

OH right .. !!所以...我如何将切片值分配给currentSource和currentDest变量,并且文件的内容是多个语句,比如C3,F3,C4,A4,C5,A1 @KavehShahbazian – Riya

回答

0

这工作

var currentSource string 
var currentDest string 

func main() { 

    file := "A1,B2\n" 
    scanner := bufio.NewScanner(strings.NewReader(file)) 
    for scanner.Scan() { 
     strs := strings.Split(scanner.Text(), ",") 

     currentSource = strs[0] 
     currentDest = strs[1] 

     fmt.Println(strs) 
    } 


} 

你确定你的文件(chessin.txt)它是确定?

Playground

+0

我的任务是读取来自文本文件和是的即时通讯非常肯定,它是好的,我不明白为什么它显示错误,值分配正确,但程序退出后。正如前面提到的问题,我会等待,我只是寻找更多的帮助没有进攻@Toni Villena – Riya

+0

@Riya,我没有得罪,对不起,如果你认为... :-) –

0

此代码是几乎相同的代码,它工作正常:

package main 

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

var currentSource string 
var currentDest string 

func main() { 

    // content of this file is (no spaces between comas, not \r or 
    // \n or any other whitespace): 
    //C3,F3,C4,A4,C5,A1 
    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(), ",") 

     if len(strs) < 2 { 
      panic(`not enough elements in the file, to proceed`) 
     } 

     currentSource = strs[0] 
     currentDest = strs[1] 

     break //(B) 
    } 

    if currentSource != "C3" { 
     panic(`currentSource IS NOT C3`) 
    } 

    if currentDest != "F3" { 
     panic(`currentDest is not F3`) 
    } 

    // if we are here, then we are good 
    fmt.Println(currentSource, currentDest) 
} 

只是要注意的break声明在(B)。这会导致for循环在第一行的第一个和第二个元素之后停止 - 不确定;但这可能是你想要的。

所以,如果程序没有达到(A)点,那么出现chessin.txt错误。

相关问题