fmt.Scanln预计换行错误 [英] fmt.Scanln expected newline error
问题描述
我试图学习Go,但坚持使用这个: http://ideone.com/hbCamr或 http://ideone.com/OvRw7t
func main(){
var i int
var f float64
var s string
$ b $,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:,er r)
}
}
这个输入:
123
123.456
每个人都喜欢冰淇淋
输出为:
读取1整数:123
读取1 float64:123.456
读取1字符串:大家
错误:扫描:预计换行
<这是预期的行为?为什么它不像C ++ getline那样工作? http://ideone.com/Wx8z5o
答案在 Scanln
:
Scanln与Scan类似,但停止在换行符处扫描,并在最终项目必须有换行符或EOF。
扫描
表现为有文档记录:
$ b
扫描扫描文本读取标准输入,将连续的空格分隔值存储为连续的参数。换行占据空间。它返回成功扫描的项目数量。如果这小于参数的数量,err会报告原因。
总结:扫描
放入每个单词(用空格分隔的字符串)转化为相应的论点,将新线视为空间。 Scanln
可以做同样的事情,但将换行符视为停止字符,在此之后不会进一步解析。
想读一行(最后 \\\
)使用
bufio.Reader
及其 ReadString
方法:
line,err:= buffer.ReadString('\\\
')
I'm trying to learn Go, but stuck with this one: http://ideone.com/hbCamr or http://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)
}
}
for this input:
123
123.456
everybody loves ice cream
the output was:
read 1 integer: 123
read 1 float64: 123.456
read 1 string: everybody
Error: Scan: expected newline
is this the expected behavior? why doesn't it work like C++ getline? http://ideone.com/Wx8z5o
The answer is in the 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
behaves as documented as well:
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.
To conclude: Scan
puts each word (a string separated by space) into a corresponding argument, treating newlines as space. Scanln
does the same but treats newlines as a stop character, not parsing any further after that.
In case you want to read a line (\n
at the end) use bufio.Reader
and its ReadString
method:
line, err := buffer.ReadString('\n')
这篇关于fmt.Scanln预计换行错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!