如何从控制台中的标准输入读取? [英] How can I read from standard input in the console?

查看:30
本文介绍了如何从控制台中的标准输入读取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从命令行读取标准输入,但我的尝试以程序在提示我输入之前退出而结束.我正在寻找相当于 C# 中的 >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('
')
    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('
')
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.

这篇关于如何从控制台中的标准输入读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆