Golang读取文本文件并从读取的值中获取一个切片。

huangapple go评论101阅读模式
英文:

Golang Read text file and take a slice from one of the read in values

问题

在下面的代码中,我希望读取一个文本文件,每行填写一个1-5的数字。我想要扫描每行并读取其中的一个值,然后判断它是否小于6,并执行相应的操作。不幸的是,我无法获取这些值的切片,它们只会以数组的形式打印出来。请问有什么建议可以修复我的代码吗?

//这部分程序将从名为"file"的文本文件中读取数据
//以了解上次选择的数字,以便第二周的食谱可以是全新的5个数字组合
f, err := os.Open("file")
if err != nil {
fmt.Println(err)
}
for {
var z int
var n int
n, err = fmt.Fscanln(f, &z)
if n == 0 || err != nil {
break
}
fmt.Println("int z:", z)
}

英文:

In my code below, I'm hoping to read a text file filled with a number 1-5 per line. I want it to scan the line and read one of values and see if its < 6 and perform an action. Unfortunately I'm unable to take a slice of the values, they only print as an array. Any advice on how i can fix my code please?

//This is the part of the program that will read from a text file named &quot;file&quot;
//To see what numbers were selected last time so the recipe for week two can be
//a completely new recipe group of 5
f, err := os.Open(&quot;file&quot;)
if err != nil {
	fmt.Println(err)
}
for {
	var z int
	var n int
	n, err = fmt.Fscanln(f, &amp;z)
	if n == 0 || err != nil {
		break
	}
	fmt.Println(&quot;int z :&quot;, z)
}

答案1

得分: 2

你的代码在我的测试中运行良好。可能文件的格式稍有不同或者位置不同?

for {
    var z int
    var n int
    n, err = fmt.Fscan(f, &z)
    if n == 0 || err != nil {
        break
    }
    fmt.Println("int z:", z)
}

实际上,这个问题的变体可以参考以下链接:
https://stackoverflow.com/questions/3751429/reading-an-integer-from-standard-input-in-golang

英文:

Your code worked fine in my test. Likely the file is formatted slightly differently or is in a different location?

for {
	var z int
	var n int
	n, err = fmt.Fscan(f, &amp;z)
	if n == 0 || err != nil {
		break
	}
	fmt.Println(&quot;int z :&quot;, z)
}

really, a variation of this question:
https://stackoverflow.com/questions/3751429/reading-an-integer-from-standard-input-in-golang

huangapple
  • 本文由 发表于 2016年2月14日 15:06:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/35389257.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定