gpt4 book ai didi

input - fmt.Scanln 预期换行错误

转载 作者:IT王子 更新时间:2023-10-29 01:51:33 29 4
gpt4 key购买 nike

我正在尝试学习 Go,但坚持使用这个:http://ideone.com/hbCamrhttp://ideone.com/OvRw7t

package main
import "fmt"

func main(){
var i int
var f float64
var s string

_, err := fmt.Scan(&i)
if err == nil {
fmt.Println("read 1 integer: ",i)
} else {
fmt.Println("Error: ",err)
}

_, err = fmt.Scan(&f)
if err == nil {
fmt.Println("read 1 float64: ",f)
} else {
fmt.Println("Error: ",err)
}
_, err = fmt.Scan(&s)
if err == nil {
fmt.Println("read 1 string: ",s)
} else {
fmt.Println("Error: ",err)
}

_, err = fmt.Scanln(&s)
if err == nil {
fmt.Println("read 1 line: ",s)
} else {
fmt.Println("Error: ",err)
}
}

对于这个输入:

123
123.456
everybody loves ice cream

输出是:

read 1 integer:  123
read 1 float64: 123.456
read 1 string: everybody
Error: Scan: expected newline

这是预期的行为吗?为什么它不像 C++ getline 那样工作? http://ideone.com/Wx8z5o

最佳答案

答案在 documentation of Scanln 中:

Scanln is similar to Scan, but stops scanning at a newline and after the final item there must be a newline or EOF.

Scan 表现为 documented还有:

Scan scans text read from standard input, storing successive space-separated values into successive arguments. Newlines count as space. It returns the number of items successfully scanned. If that is less than the number of arguments, err will report why.

总结:Scan 将每个单词(由空格分隔的字符串)放入相应的参数中,将换行符视为空格。 Scanln 做同样的事情,但将换行符视为停止字符,之后不再进一步解析。

如果你想阅读一行(\n 在末尾)使用 bufio.Reader 及其 ReadString方法:

line, err := buffer.ReadString('\n')

关于input - fmt.Scanln 预期换行错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24005899/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com