Shuumatsu
Shuumatsu

Reputation: 672

How to use fmt.scanln read from a string separated by spaces

Want "30 of month" but get "30"

package main

import "fmt"

func main() {
    var s string
    fmt.Scanln(&s)
    fmt.Println(s)
    return
}

$ go run test.go
31 of month
31

Scanln is similar to Scan, but stops scanning at a newline and after the final item there must be a newline or EOF.

Upvotes: 15

Views: 29659

Answers (4)

arturfil
arturfil

Reputation: 450

I'm going to add to @trquoccuong answer so that this is visible for everyone.

package main
import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    if scanner.Scan() {
        s := scanner.Text()
        fmt.Println(s)
    }
    if err := scanner.Err(); err != nil {
        os.Exit(1)
    }
}

This way your code doesn't get stuck in the forloop and continues with the next task.

Upvotes: 0

Venkataramana Madugula
Venkataramana Madugula

Reputation: 14119

Here is the working program

package main

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

func main() {
    var strInput string
    fmt.Println("Enter a string ")
    scanner := bufio.NewScanner(os.Stdin)

    if scanner.Scan() {
        strInput = scanner.Text()
    }
    
    fmt.Println(strInput)
}

which reads strings like " d skd a efju N" and prints the same string as output.

Upvotes: 5

yee
yee

Reputation: 1985

If you really want to include the spaces, you may consider using fmt.Scanf() with format %q a double-quoted string safely escaped with Go syntax , for example:

package main

import "fmt"

func main() {
    var s string
    fmt.Scanf("%q", &s)
    fmt.Println(s)
    return
}

Run it and:

$ go run test.go
"31 of month"
31 of month

Upvotes: 9

trquoccuong
trquoccuong

Reputation: 2873

The fmt Scan family scan space-separated tokens.

package main

import (
    "fmt"
)

func main() {
    var s1 string
    var s2 string
    fmt.Scanln(&s1,&s2)
    fmt.Println(s1)
    fmt.Println(s2)
    return
}

You can try bufio scan

package main
import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    for scanner.Scan() {
        s := scanner.Text()
        fmt.Println(s)
    }
    if err := scanner.Err(); err != nil {
        os.Exit(1)
    }
}

Upvotes: 11

Related Questions