How to read a string with fmt.Scan after using bufio for reading a line in Go?

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

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(&quot;%s&quot;, &amp;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 (
	&quot;bufio&quot;
	&quot;fmt&quot;
	&quot;os&quot;
)

func main() {
	reader := bufio.NewReader(os.Stdin)

	var str string
	inp, _ := reader.ReadString(&#39;\n&#39;)
	fmt.Scanf(&quot;%s&quot;, &amp;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 (
	&quot;bufio&quot;
	&quot;fmt&quot;
	&quot;os&quot;
)

func main() {
	reader := bufio.NewReader(os.Stdin)

	var str string
	inp, _ := reader.ReadString(&#39;\n&#39;)
	fmt.Scanf(&quot;%s&quot;, &amp;str)

	fmt.Print(inp)
	fmt.Printf(&quot;%s\n&quot;, str)
}

How to read a string with fmt.Scan after using bufio for reading a line in Go?

huangapple
  • 本文由 发表于 2021年10月12日 13:56:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/69535702.html
匿名

发表评论

匿名网友

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

确定