英文:
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#
-
我想知道为什么在 Golang 中,
123
被插入到我的 bash 命令中。但是在 C 中没有?有什么区别吗?(我知道在 stdin 中有一些字符保留) -
我想知道如何使 Golang 的行为像 C 一样?
英文:
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#
-
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) -
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论