Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read from standard input in the console?

Tags:

go

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#.

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) } 
like image 635
Dante Avatar asked Jan 03 '14 02:01

Dante


People also ask

How do you read input and standard input?

One popular way to read input from stdin is by using the Scanner class and specifying the Input Stream as System.in. For example: Scanner scanner = new Scanner(System.in); String userString = scanner. next(); int userInt = scanner.

Which function is read input from console?

A string type of data is defined and every line of the string is read using the 'readLine' function. The input is given from the standard input, and relevant message is displayed on the console.


2 Answers

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) 

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)

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

like image 84
Linear Avatar answered Sep 19 '22 04:09

Linear


You can as well try:

scanner := bufio.NewScanner(os.Stdin) for scanner.Scan() {     fmt.Println(scanner.Text()) }  if scanner.Err() != nil {     // Handle error. } 
like image 23
Helin Wang Avatar answered Sep 17 '22 04:09

Helin Wang