Home > Backend Development > Golang > Why Doesn't `reader.ReadString('\n')` Reliably Handle Newline Delimiters in Go?

Why Doesn't `reader.ReadString('\n')` Reliably Handle Newline Delimiters in Go?

DDD
Release: 2025-01-02 17:47:42
Original
238 people have browsed it

Why Doesn't `reader.ReadString('n')` Reliably Handle Newline Delimiters in Go?

Why reader.ReadString Doesn't Properly Handle Delimeters

In the provided Go program, the issue arises when using reader.ReadString('n') to read a line of text. When the user enters "Alice" or "Bob," the input text contains an additional newline character, causing a mismatch with the specified delimiter ('n').

Solution: Trim or Use ReadLine

To resolve this issue, you can either trim the whitespace (including the newline character) after reading the string or use reader.ReadLine() directly.

Trimming Whitespace with strings.TrimSpace

package main

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

func main() {
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Who are you? \n Enter your name: ")
    text, _ := reader.ReadString('\n')
    if aliceOrBob(strings.TrimSpace(text)) {
        fmt.Printf("Hello, ", text)
    } else {
        fmt.Printf("You're not allowed in here! Get OUT!!")
    }
}
Copy after login

Using ReadLine

package main

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

func main() {
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Who are you? \n Enter your name: ")
    text, _, _ := reader.ReadLine()
    if aliceOrBob(string(text)) {
        fmt.Printf("Hello, ", text)
    } else {
        fmt.Printf("You're not allowed in here! Get OUT!!")
    }
}
Copy after login

By properly handling the input string, the program can now correctly identify whether the user's name is "Alice" or "Bob" and respond accordingly.

The above is the detailed content of Why Doesn't `reader.ReadString('\n')` Reliably Handle Newline Delimiters in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template