Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fmt: Scanf's err puts extraneous '\n' if arg is small #13743

Closed
bassu opened this issue Dec 27, 2015 · 3 comments
Closed

fmt: Scanf's err puts extraneous '\n' if arg is small #13743

bassu opened this issue Dec 27, 2015 · 3 comments

Comments

@bassu
Copy link

@bassu bassu commented Dec 27, 2015

Scanf doesn't seem to care about newline in format. It's also putting an extraneous \n in err.Error() if scanned input is longer than expected.

func main() {
    var input int
    _, err := fmt.Scanf("%d\n", &input)
    if err != nil {
        fmt.Printf("%q", err)
    }
}

With "golang" as input, the "olang" gets dragged to a newline in err. This is contrary to what the documentation says:

Scanf, Fscanf and Sscanf require that (after skipping spaces) newlines in the format are matched by newlines in the input and vice versa. 
With that proviso, text in the format string must match the input text; scanning stops if it does not, with the return value of the function indicating the number of arguments scanned
bash-3.2$ go run test.go
golang
"expected integer"bash-3.2$ olang
bash: olang: command not found
bash-3.2$
@bradfitz bradfitz changed the title Scanf's err puts extraneous '\n' if arg is small fmt: Scanf's err puts extraneous '\n' if arg is small Dec 27, 2015
@bradfitz
Copy link
Contributor

@bradfitz bradfitz commented Dec 27, 2015

/cc @robpike

@mdempsky
Copy link
Member

@mdempsky mdempsky commented Dec 27, 2015

"olang" isn't in err. What's happening is fmt.Scanf is reading one byte at a time, it reads the 'g' character, realizes that's not an integer character, then your Go program exits after printing "expected integer". The remaining "olang" characters are still buffered in the terminal's input, and are read and interpreted by your shell.

This seems to be working as intended.

@mdempsky mdempsky closed this Dec 27, 2015
@bassu
Copy link
Author

@bassu bassu commented Dec 27, 2015

@mdempsky That's what I realized after filing the bug. But what's odd is, it happens only if I print the err. It doesn't happen if I use input redirection, of course or if err is not printed at all!

@golang golang locked and limited conversation to collaborators Dec 29, 2016
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
4 participants
You can’t perform that action at this time.