英文:
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 "file"
//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("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)
}
答案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, &z)
if n == 0 || err != nil {
break
}
fmt.Println("int z :", z)
}
really, a variation of this question:
https://stackoverflow.com/questions/3751429/reading-an-integer-from-standard-input-in-golang
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论