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

时间:2019-02-25 13:13:58

标签: c vbscript

我知道有关此主题的其他帖子。但是,在对所有内容进行审查之后,我的情况似乎仍然存在问题。

当前,我正在使用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

我使用sprintf()命令合并了system()命令的总字符串。

sprintf(command, "cmd /c spraak.vbs \"Welcome\"");
system(command);

这里使用的代码就像一个超级按钮。但是,当我尝试使用变量作为参数时(“欢迎使用”)。它只说“空”。

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

可能是什么问题?

下面的完整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;
}

2 个答案:

答案 0 :(得分:5)

问题是这样的:

char command[] = "";

这将创建一个单个字符的数组,并且单个字符是字符串终止符'\0'。等于

char command[1] = { '\0' };

当您使用sprintf时,您越写越多,将得到undefined behavior

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

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

答案 1 :(得分:0)

sprintf需要一个已经分配的缓冲区,其大小要足以放入结果中。您的char command[] = ""是一个长度为1的字符数组(只是终止的null),太短了以至于取得全部结果。

您可能想尝试使用

char command[50];

相反。请注意,在实际应用中,50应根据要存储的数据适当确定。为此,您可以使用snprintf代替sprintf来计算所需的缓冲区大小。