C和Go在程序退出时stdin中仍有剩余内容时有什么区别?

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

What's the difference between C and Go when there are remains in stdin on programs exits

问题

main.c

#include <stdio.h>

int main() {
    int k;
    scanf("%d", &k);
    return 0;
}

main.go

package main

import "fmt"

func main() {
    var n int
    fmt.Scan(&n)
}
root@82da6559c1c0:/code# go run main.go 
123x123
root@82da6559c1c0:/code# 123
bash: 123: command not found
root@82da6559c1c0:/code# gcc main.c -o main
root@82da6559c1c0:/code# ./main
123x123
root@82da6559c1c0:/code# 
  1. 我想知道为什么在 Golang 中,123 被插入到我的 bash 命令中。但是在 C 中没有?有什么区别吗?(我知道在 stdin 中有一些字符保留)

  2. 我想知道如何使 Golang 的行为像 C 一样?

英文:

main.c

#include &lt;stdio.h&gt;

int main() {
    int k;
    scanf(&quot;%d&quot;, &amp;k);
    return 0;
}

main.go

package main

import &quot;fmt&quot;

func main() {
	var n int
	fmt.Scan(&amp;n)
}
root@82da6559c1c0:/code# go run main.go 
123x123
root@82da6559c1c0:/code# 123
bash: 123: command not found
root@82da6559c1c0:/code# gcc main.c -o main
root@82da6559c1c0:/code# ./main
123x123
root@82da6559c1c0:/code# 
  1. I want to konw why in Golang, 123 was inserted into my bash command. But in C it didn't? Was there any differecces? (I konw there were some characters remained in stdin)

  2. I want to konw how can I make Golang behave like C does?

答案1

得分: 1

默认情况下,C语言中的stdin是带缓冲的,所以你的scanf会导致更大的输入读取(进入缓冲区)。

在Go语言中,os.Stdin没有 缓冲的。如果你想要实现与C程序中相同的结果,你可以将stdin包装在一个bufio.Reader中,尽管这是否与你使用的C标准库完全相同的行为需要进行测试。

英文:

By default, stdin is buffered in C, so your scanf causes a larger read of the input (into a buffer).

In Go, os.Stdin is not buffered. If you want to achieve the same result as you see in the C program, you can wrap stdin in a bufio.Reader, although whether that has exactly the same behavior as whatever C standard library you're using will need testing.

huangapple
  • 本文由 发表于 2022年10月23日 18:15:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/74170309.html
匿名

发表评论

匿名网友

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

确定