英文:
How to use fmt.scanln read from a string separated by spaces
问题
想要获取“30 of month”,但得到了“30”。
package main
import "fmt"
func main() {
var s string
fmt.Scanln(&s)
fmt.Println(s)
return
}
$ go run test.go
31 of month
31
> Scanln 类似于 Scan,但在换行符处停止扫描,并且在最后一项之后必须有一个换行符或 EOF。
英文:
Want "30 of month" but get "30"
package main
import "fmt"
func main() {
var s string
fmt.Scanln(&s)
fmt.Println(s)
return
}
$ go run test.go
31 of month
31
>Scanln is similar to Scan, but stops scanning at a newline and after the final item there must be a newline or EOF.
答案1
得分: 11
The fmt Scan family scan space-separated tokens.
package main
import (
"fmt"
)
func main() {
var s1 string
var s2 string
fmt.Scanln(&s1,&s2)
fmt.Println(s1)
fmt.Println(s2)
return
}
你可以尝试使用 bufio scan
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
s := scanner.Text()
fmt.Println(s)
}
if err := scanner.Err(); err != nil {
os.Exit(1)
}
}
英文:
The fmt Scan family scan space-separated tokens.
package main
import (
"fmt"
)
func main() {
var s1 string
var s2 string
fmt.Scanln(&s1,&s2)
fmt.Println(s1)
fmt.Println(s2)
return
}
You can try bufio scan
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
s := scanner.Text()
fmt.Println(s)
}
if err := scanner.Err(); err != nil {
os.Exit(1)
}
}
答案2
得分: 9
如果你真的想包含空格,你可以考虑使用fmt.Scanf()
和格式%q
,例如:
package main
import "fmt"
func main() {
var s string
fmt.Scanf("%q", &s)
fmt.Println(s)
return
}
运行它:
$ go run test.go
"31 of month"
31 of month
英文:
If you really want to include the spaces, you may consider using fmt.Scanf()
with format %q a double-quoted string safely escaped with Go syntax
, for example:
package main
import "fmt"
func main() {
var s string
fmt.Scanf("%q", &s)
fmt.Println(s)
return
}
Run it and:
$ go run test.go
"31 of month"
31 of month
答案3
得分: 4
这是一个工作中的程序:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
var strInput string
fmt.Println("输入一个字符串:")
scanner := bufio.NewScanner(os.Stdin)
if scanner.Scan() {
strInput = scanner.Text()
}
fmt.Println(strInput)
}
该程序读取像 " d skd a efju N" 这样的字符串,并将相同的字符串作为输出打印出来。
英文:
Here is the working program
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
var strInput string
fmt.Println("Enter a string ")
scanner := bufio.NewScanner(os.Stdin)
if scanner.Scan() {
strInput = scanner.Text()
}
fmt.Println(strInput)
}
which reads strings like " d skd a efju N"
and prints the same string as output.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论