Scanf()和Scanln()之间有什么区别?

huangapple go评论70阅读模式
英文:

The are the differences between Scanf() and Scanln()?

问题

请看下面的代码:

  1. 第一个代码块使用了Scanf()函数来读取输入。Scanf()函数会根据指定的格式从标准输入中读取数据,并将其存储到相应的变量中。在这个例子中,它会读取一个整数并将其存储到变量j中。

  2. 第二个代码块使用了Scanln()函数来读取输入。Scanln()函数会从标准输入中读取一行数据,并将其存储到相应的变量中。在这个例子中,它会读取一行整数并将其存储到变量j中。

两个函数的主要区别在于读取的方式。Scanf()函数根据指定的格式进行读取,而Scanln()函数则按行读取。在第一个代码块中,当输入为1时,Scanf()函数会读取整数1并将其存储到变量j中。而在第二个代码块中,当输入为1时,Scanln()函数会读取整行数据"1

",并将其存储到变量j中。

希望这些信息对你有帮助!

英文:

please look at the code below:

  1. The First
  • code
    for {
    		fmt.Println("--------start--------")
    		fmt.Println("please input j:")
    		var j int
    		fmt.Scanf("%v", &j)
    		fmt.Println("your intput j:", j)
    		fmt.Println("--------end--------\n")
    	}
  • resut
D:\project\go-workspace\src\go_code\chapter10>go run demo07/test.go
--------start--------
please input j:
1
your intput j: 1
--------end--------

--------start--------
please input j:
your intput j: 0
--------end--------

--------start--------
please input j:

  1. The Second
    for {
    	fmt.Println("--------start--------")
    	fmt.Println("please input j: ")
    	var j int
    	fmt.Scanln(&j)
    	fmt.Println("your intput j:", j)
    	fmt.Println("--------end--------\n")
    }
  • result
D:\project\go-workspace\src\go_code\chapter10>go run demo07/test.go
--------start--------
please input j:
1<p>
your intput j: 1
--------end--------

--------start--------
please input j:

I don't know why this is happening,

and I want know more details between the Scanf() and Scanln()!

Hope someone can help me, thanks~

答案1

得分: 1

这两个函数的区别在于它们对标准输入的期望不同。

  • Scanf 期望你的输入与提供的格式字符串匹配,格式说明符(或“动词”)必须与给定的参数数量相匹配。
  • Scanln 期望你的输入由换行符确定。此外,分隔的字符串数量应与提供的参数数量相匹配。

文档 对此非常清楚。

英文:

The differences of these two functions are in the expectations they have towards the standard input.

  • Scanf expects your input to match the provided format string, which can have an arbitrary layout. Format specifiers (or 'verbs') must match the number of given arguments.
  • Scanln expects your input to be determined by a newline signal. Additionally the number of separated strings should match the number of provided arguments.

The documentation is very clear on that.

huangapple
  • 本文由 发表于 2021年7月3日 00:29:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/68228610.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定