将字符串变量传递给C中包含system()命令的函数

RAH*_*RAH 0 c vbscript

我知道关于这个主题的其他帖子.但在审查了所有这些内容后,我的案例似乎仍然存在问题.

目前我正在使用a Vbscript将字符串转换为语音的"字符串到语音"功能.(spraak.vbs)VBsript保存在与C代码相同的文件夹中.

带有1个参数的`VBscript文件的内容

rem String to speech  
Set spkArgs = WScript.Arguments 
arg1 = spkArgs(0)
set speech =  Wscript.CreateObject("SAPI.spvoice") 
speech.speak arg1
Run Code Online (Sandbox Code Playgroud)

使用sprintf()命令,我将system()命令的总字符串组合在一起.

sprintf(command, "cmd /c spraak.vbs \"Welcome\"");
system(command);
Run Code Online (Sandbox Code Playgroud)

这里使用的代码就像一个魅力.但是当我尝试使用变量作为我的参数时("欢迎").它只说"空".

char text = "\"Welcome\""
sprintf(command, "cmd /c spraak.vbs %s", text);
system(command);
Run Code Online (Sandbox Code Playgroud)

可能是什么问题呢?

完整的C代码如下:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("Test\n");
    char text[] = "\"Welcome\"";
    char command[] = "";
    printf("%s\n", text);
         sprintf(command, "cmd /c spraak.vbs \"Welcome\"");
         system(command);
        sprintf(command, "cmd /c spraak.vbs %s", text);
        system(command);
    printf("Test2\n");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Som*_*ude 5

问题是这样的:

char command[] = "";
Run Code Online (Sandbox Code Playgroud)

这会创建一个单个字符的数组,并且该单个字符是字符串终止符'\0'.它等于

char command[1] = { '\0' };
Run Code Online (Sandbox Code Playgroud)

当你使用sprintf时写出越界,你将有未定义的行为.

要解决这个问题,请使用固定大小的数组,并使用它snprintf来避免缓冲区溢出:

char command[128];
snprintf(command, sizeof command, "cmd /c spraak.vbs %s", text);
Run Code Online (Sandbox Code Playgroud)