如何从控制台中的标准输入中读取?

问题描述:

我想从命令行读取标准输入,但是在提示我输入之前,我的尝试以结束程序退出而告终.我正在寻找 Console.ReadLine().

I would like to read standard input from the command line, but my attempts have ended with the program exiting before I'm prompted for input. I'm looking for the equivalent of Console.ReadLine() in C#.

这是我目前拥有的:

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Enter text: ")
    text, _ := reader.ReadString('\n')
    fmt.Println(text)

    fmt.Println("Enter text: ")
    text2 := ""
    fmt.Scanln(text2)
    fmt.Println(text2)

    ln := ""
    fmt.Sscanln("%v", ln)
    fmt.Println(ln)
}

我不确定块出了什么问题

I'm not sure what's wrong with the block

reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter text: ")
text, _ := reader.ReadString('\n')
fmt.Println(text)

在我的计算机上正常工作.但是,对于下一个块,您需要一个指向要为其分配输入的变量的指针.尝试将fmt.Scanln(text2)替换为fmt.Scanln(&text2).不要使用Sscanln,因为它会解析内存中已存在的字符串,而不是stdin中的字符串.如果您想做类似您想做的事情,请将其替换为fmt.Scanf("%s", &ln)

As it works on my machine. However, for the next block you need a pointer to the variables you're assigning the input to. Try replacing fmt.Scanln(text2) with fmt.Scanln(&text2). Don't use Sscanln, because it parses a string already in memory instead of from stdin. If you want to do something like what you were trying to do, replace it with fmt.Scanf("%s", &ln)

如果仍然无法解决问题,您的罪魁祸首可能是一些奇怪的系统设置或错误的IDE.

If this still doesn't work, your culprit might be some weird system settings or a buggy IDE.