英文:
How to read a string with fmt.Scan after using bufio for reading a line in Go?
问题
我使用 bufio.NewReader(os.Stdin)
读取了一行,然后使用 fmt.Scanf
读取了一个字符串。
package main
import (
"fmt"
"bufio"
"os"
)
func main() {
reader := bufio.NewReader(os.Stdin)
var str string
inp, _ := reader.ReadString('\n')
fmt.Scanf("%s", &str)
fmt.Println(inp)
fmt.Printf(str)
}
输入:
This is a sentence.
John
我期望的输出应该像上面那样,但实际上并不是这样。
输出:
This is a sentence.
实际上,fmt.Scanf("%s", &str)
并不起作用。
问题是什么?我该如何解决它?
英文:
I read a line with bufio.NewReader(os.Stdin)
, then I read a string with fmt.Scanf
.
package main
import (
"fmt"
"bufio"
"os"
)
func main() {
reader := bufio.NewReader(os.Stdin)
var str string
inp, _ := reader.ReadString('\n')
fmt.Scanf("%s", &str)
fmt.Println(inp)
fmt.Printf(str)
}
Input:
This is a sentence.
John
I expect the output to be like above, but it isn't.<br />
Output:
This is a sentence.
actually fmt.Scanf("%s", &str)
doesn't work.<br />
What is the problem? and How can I fix it?
答案1
得分: 1
reader.ReadString(delim)函数会读取从当前位置到分隔符(包括分隔符)之间的所有内容。因此,在两个输入之间会添加换行符"\n"。而fmt.Printf(str)函数在末尾不会添加换行符"\n",所以第二个输出会与下一个被打印到标准输出的内容连在一起。
以下是按照你要求运行的代码:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
reader := bufio.NewReader(os.Stdin)
var str string
inp, _ := reader.ReadString('\n')
fmt.Scanf("%s", &str)
fmt.Print(inp)
fmt.Printf("%s\n", str)
}
输入:
some line
John
输出:
some line
John
以上是按照你要求运行的代码和输出结果。
英文:
reader.ReadString(delim) reads everything up to the delim, including the delimiter. So, it adds \n between two inputs. fmt.Printf(str) does not have \n in the end, so the second output sticks to the next thing printed to stdout.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
reader := bufio.NewReader(os.Stdin)
var str string
inp, _ := reader.ReadString('\n')
fmt.Scanf("%s", &str)
fmt.Println(inp)
fmt.Printf(str)
}
Input:
some line
John
Output:
some line
John
Below is the code that runs as you want it to.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
reader := bufio.NewReader(os.Stdin)
var str string
inp, _ := reader.ReadString('\n')
fmt.Scanf("%s", &str)
fmt.Print(inp)
fmt.Printf("%s\n", str)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论