douzhuanfen5923 2018-09-27 17:21
浏览 60
已采纳

从Golang应用发送字符串时出现意外的StrComp结果

In my code below I've set up a ReadString which reads user input and passes it along in a exec.Command.

This works just fine, but when I try to compare the string with a hardcoded string in vbscript (in this case I'm comparing it to "hello") it always fails even when the user input is "hello" as well.

If I just run the vbscript through the command line like this however...

 cscript.exe script.vbs hello

...then the StrComp works as intended so I suspect that it's either a data type issue or there's some extra character that's passed along in the golang app.

Here's the main.go:

package main

import (
    "fmt"
    "os/exec"
    "bufio"
    "os"
)

func main() {

    buf := bufio.NewReader(os.Stdin)

    fmt.Print("Type something: ")
    text, err := buf.ReadString('
')
    if err != nil {
        fmt.Println(err)
    } else {
        args := []string{"./script.vbs", string(text)}
        exec.Command("cscript.exe", args...).Run()
    }
}

And here's the script.vbs

MsgBox(WScript.Arguments(0))

If StrComp(WScript.Arguments(0), "hello") = 0 Then
    MsgBox("it's the same")
Else
    MsgBox("It's not the same...")
End If
  • 写回答

1条回答 默认 最新

  • duangao7133 2018-09-27 17:59
    关注

    When working with windows, line endings are " ". I don't know whether ReadString() should remove the delimiter, but even then text will contain an invisible . Use strings.TrimSpace to be on the save side:

    package main
    
    import (
        "fmt"
        "os/exec"
        "bufio"
        "os"
        "strings"
    )
    
    func main() {
    
        buf := bufio.NewReader(os.Stdin)
    
        fmt.Print("Type something: ")
        text, err := buf.ReadString('
    ')
        fmt.Printf("0 got: %T %v %q
    ", text, text, text)
        text = strings.TrimSpace(text)
        fmt.Printf("1 got: %T %v %q", text, text, text)
        if err != nil {
            fmt.Println(err)
        } else {
            args := []string{"./script.vbs", string(text)}
            exec.Command("cscript.exe", args...).Run()
        }
    }
    

    output (of main; use your imagination for the VBScript MsgBoxes):

    main
    Type something: hello
    0 got: string hello
     "hello
    "
    1 got: string hello "hello"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥15 小红薯封设备能解决的来
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答
  • ¥20 在本地部署CHATRWKV时遇到了AttributeError: 'str' object has no attribute 'requires_grad'
  • ¥15 vue+element项目中多tag时,切换Tab时iframe套第三方html页面需要实现不刷新
  • ¥50 深度强化学习解决能源调度问题
  • ¥15 一道计算机组成原理问题