英文:
In Go language how to take input step by step from file as like freopen in c/c++
问题
package main
import (
"fmt"
"os"
)
func main() {
file, err := os.Open("in.txt")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
var n, val, sum int
fmt.Fscanf(file, "%d", &n)
for i := 0; i < n; i++ {
fmt.Fscanf(file, "%d", &val)
sum += val
}
fmt.Println(sum)
}
在Go语言中,你可以使用os
包中的Open
函数打开文件,并使用Fscanf
函数从文件中读取数据。这样你就不需要手动提供大量的数据或将其添加到代码中。
英文:
#include<stdio.h>
int main()
{
freopen("in.txt", "r", stdin);
int n, val, sum=0;
scanf("%d", &n);
for(int i=0; i<n; i++)
{
scanf("%d", &val);
sum += val;
}
printf("%d\n", sum);
}
Input (in.txt):
5
1 2 3 4 5
Output:
15
In C language above program will automatically take data from in.txt file. I do not need to provide data in console.
Is there any way to do this in GO language? So that I do not need to provide huge amount of data manually or add that in code.
答案1
得分: 3
你不需要仅从标准输入扫描,可以直接打开文件。
fmt
包提供了一系列 fmt.Fscan*
函数来实现这个功能。
英文:
You don't need to scan only from stdin, open the file directly.
The fmt
package has a series of fmt.Fscan*
functions for this.
答案2
得分: 2
你的C程序只是逐个扫描标记。当然,在Go语言中有很多实现这个功能的方法。我建议使用bufio
包,但实际上你只需要一个读取器和一个将字符串转换为整数的工具。下面是一个类似于你的C程序的示例。
import "bufio"
import "strconv"
file, err := os.Open("in.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
base := 0
if scanner.Scan() {
base += strconv.Atoi(scanner.Text())
}
scanner.Split(bufio.ScanWords)
for scanner.Scan() {
base += strconv.Atoi(scanner.Text())
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
fmt.Println(base)
以上是一个类似于你的C程序的示例,实现了逐个扫描标记的功能。
英文:
Your C program is just scanning the tokens one by one. Of course there are many ways to accomplish this in Go. I'd recommend the bufio
package but really all you need is a reader and something to convert string to int. Below is an example that is similar to your C program.
import "bufio"
import "strconv"
file, err := os.Open("in.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
base := 0
if scanner.Scan() {
base += strconv.Atoi(scanner.Text())
}
scanner.Split(bufio.ScanWords)
for scanner.Scan() {
base += strconv.Atoi(scanner.Text())
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
fmt.Println(base)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论