英文:
why fmt.Scanf("%s", &name) print the previous value
问题
我为了学习而编写了这段代码:-
package main
import (
"fmt"
"strconv"
)
func main() {
for {
name := ""
fmt.Print("输入:")
fmt.Scanf("%s", &name)
b1, _ := strconv.ParseBool(name)
fmt.Printf("%T, %v\n", b1, b1)
}
}
输出:
输入:True
bool, true
输入:bool, false
输入:
为什么会有额外的"输入:bool, false"行?
编辑:
这个问题在Windows的Powershell、cmd和bash中会出现,但在wsl中不会。
编辑:这是相同的问题,但是这是一个不同的问题。我在我的答案中提到的解决方法已经过时了,我必须确认和检查一下。
英文:
I make this code for learning:-
package main
import (
"fmt"
"strconv"
)
func main() {
for {
name := ""
fmt.Print("Enter : ")
fmt.Scanf("%s", &name)
b1, _ := strconv.ParseBool(name)
fmt.Printf("%T, %v\n", b1, b1)
}
}
output:
> Enter : True
>
> bool, true
>
> Enter : bool, false
>
> Enter :
why there is an extra "Enter: bool, false" line?
edit:
this will happen in Powershell, cmd and bash in windows but not in wsl.
Edit: this was the same issue but it is a different question. and the solution there as I mentioned is outdated, It was updated after I mentioned it in my answer but I have to confirm and check that.
答案1
得分: 2
我假设你正在使用某个集成开发环境(IDE)。
有时它们会搞乱控制台输出,尝试直接从本机终端运行。或者使用VS Code。
英文:
I assume you're using some IDE.
sometimes they mess up the console output, try to run directly from native terminal instead. Or use vscode.
答案2
得分: 0
编辑:正如 @Daniel Farrell 提到的,这个问题在很多年前就已经修复了,但是我在 Windows 终端(包括 Powershell、cmd 和 bash)中遇到了这个问题,而且在 cmder 终端也有同样的问题。
在 wsl 和 MobaXterm 终端中不会出现这个问题,我没有在其他终端上进行进一步的检查。
我必须提到,有一个旧的“已弃用”的解决方法,即在“%s\n”格式字符串中添加新行。就像这个答案中所示。
所以下面的代码将在所有终端中工作:
package main
import (
"fmt"
"strconv"
)
func main() {
for {
var name string
fmt.Print("Enter : ")
fmt.Scanf("%s\n", &name)
b1, _ := strconv.ParseBool(name)
fmt.Printf("%T, %v \n", b1, b1)
}
}
英文:
Edit: as @Daniel Farrell mentioned this issue fixed many years ago., but I'm getting this issue in Windows-terminal with (Powershell, cmd, and bash) and the same issue with cmder terminal.
this will not happen with wsl and with MobaXterm terminal, I did not make further checking with other terminals.
I have to mention that there is an old "deprecated" workaround by adding the new line in the "%s\n" format strings. As in this answer
so the code below will work in all terminals:
package main
import (
"fmt"
"strconv"
)
func main() {
for {
var name string
fmt.Print("Enter : ")
fmt.Scanf("%s\n", &name)
b1, _ := strconv.ParseBool(name)
fmt.Printf("%T, %v \n", b1, b1)
}
}
答案3
得分: -1
我已经重新输入了你的代码,并得到了与Sombriks相同的结果,你可能是误按了回车键。
这是一个截图:
package main
import (
"fmt"
"strconv"
)
func main() {
for {
name := ""
fmt.Print("请输入:")
fmt.Scanf("%s", &name)
b, _ := strconv.ParseBool(name)
fmt.Printf("%T - %v\n", b, b)
}
}
英文:
i had retype your code and i got the same as Sombriks, you must have pressed enter key by mistake.
here is a screenshot
package main
import (
"fmt"
"strconv"
)
func main() {
for {
name := ""
fmt.Print("Enter: ")
fmt.Scanf("%s", &name)
b, _ := strconv.ParseBool(name)
fmt.Printf("%T - %v\n", b, b)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论