In Go language how to take input step by step from file as like freopen in c/c++

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

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&lt;stdio.h&gt;

int main()
{
    freopen(&quot;in.txt&quot;, &quot;r&quot;, stdin);

    int n, val, sum=0;
    scanf(&quot;%d&quot;, &amp;n);

    for(int i=0; i&lt;n; i++)
    {
        scanf(&quot;%d&quot;, &amp;val);
        sum += val;
    }

    printf(&quot;%d\n&quot;, 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 &quot;bufio&quot;
import &quot;strconv&quot;

file, err := os.Open(&quot;in.txt&quot;)
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)

huangapple
  • 本文由 发表于 2015年8月28日 01:59:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/32256407.html
匿名

发表评论

匿名网友

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

确定