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 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入