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

Issue

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. 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?

Solution

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.

Answered By – Paul Hankin

Answer Checked By – Senaida (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.