fmt.Scanf不会占用字符串末尾的所有字符 [英] fmt.Scanf does not consume all the characters through the end of the string
问题描述
package main
import "fmt"
func main(){
var i int
fmt.Print("input integer: ")
fmt.Scanf("%d", &i)
}
当我从终端运行这个小程序并输入为
when I run this small program from terminal and give input as
input integer: 3.ls
它还执行 ls
命令或当我输入
it also executes ls
command
or when i give input
input integer: 665.cd someDir
它执行 cd someDir
.这是Scanf在go中的正常行为吗?这在C语言中不会发生.有人可以解释发生了什么事.
it executes cd someDir
.
Is this normal behavior with Scanf in go.This does not happen in C.
Can someone explain what's happening.
推荐答案
您的 fmt.Scanf(%d",& i)
调用仅从输入中解析一个整数,它直到行尾才使用.
Your fmt.Scanf("%d", &i)
call only parses an integer from the input, it does not consume input until the end of line.
如果输入 3.ls
,则将 3
解析为十进制数字,并使用.
并将停止扫描.您的应用程序到此结束,因此其余部分( ls
和换行符)将由您的shell执行.
If you input 3.ls
, then 3
is parsed as the decimal number, and .
is consumed and will stop the scanning. Your app ends here, so the rest (ls
and the newline) will be executed by your shell.
使用 bufio.Scanner
来阅读行,例如:
fmt.Print("input string: ")
scanner := bufio.NewScanner(os.Stdin)
if !scanner.Scan() {
return // no input
}
var i int
fmt.Sscanf(scanner.Text(), "%d", &i)
fmt.Println("Entered:", i)
查看相关内容:告诉我这是怎么回事代码GOLANG
这篇关于fmt.Scanf不会占用字符串末尾的所有字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!