如何从控制台线读取输入? [英] How to read input from console line?

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

问题描述

我想从命令行读取输入,但是在提示输入之前,我的尝试已经结束,程序退出。我正在寻找相当于 Console.ReadLine( )在C#中。

I would like to read 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#.

这是我目前所拥有的:

This is what I currently have:

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)
}


推荐答案

我不确定块有什么问题

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

它在我的机器上工作。但是,对于下一个块,您需要一个指向要分配输入的变量的指针。尝试用 fmt.Scanln(& text2)替换 fmt.Scanln(text2)。不要使用 Sscanln ,因为它解析已经在内存中的字符串而不是标准输入。如果你想做一些你想做的事情,把它替换为 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天全站免登陆