2013-07-13 100 views
1

您好,我的C程序有一个小问题。C帮助使用批处理系统功能

#include<stdio.h> 

int main (int argc, char **argv) 
{ 
    char buff[120]; 
    char text; 

    printf("Enter your name: "); 
    gets(buff); 
    text = sprintf(buff, "echo StrText=\"%s\" > spk.vbs"); 
    system(text); 
    system("echo set ObjVoice=CreateObject(\"SAPI.SpVoice\") >> spk.vbs"); 
    system("echo ObjVoice.Speak StrText >> spk.vbs"); 
    system("start spk.vbs"); 
    return 0; 
} 

如何从用户获取输入并将其应用于system()函数中?我是C新手,我主要是一个批处理编码器,我试图将一些应用程序移植到C,所以任何人都可以告诉我在不使用系统函数的情况下编写此应用程序?

在此先感谢。

+0

而不是使用回声,你应该使用的fwrite的WinExec和(窗口)启动脚本 – Alexis

+0

顺便说一句,你不是自相矛盾了一点? _如何从用户获得输入并将其应用于system()函数中?_然后_不使用系统函数?_是否要使用'system'? – Nobilis

+0

是的,我很抱歉。确实如此。我如何从用户获得输入并将其写入文件然后执行? –

回答

0

添加到您的包括:

#include <string.h> 

更改char text;char text[120]; - 必须是一个数组,而不是单个字符

然后更换getsfgets

fgets(buff, sizeof(buff), stdin); /* for sizeof(buff) to work buff and fgets must be in the same scope */ 

buff[strlen(buff) - 1] = '\0'; /* this will trim the newline character for you */ 

最后,在将格式化为您的目的之后,您通过textsystem (可能类似):

sprintf(text, "echo StrText=\"%s\" > spk.vbs", buff); 

这是你在找什么?

注意:您还应该为system致电#include <stdlib.h>。总是用警告编译(如果你在Linux上,则为gcc -Wall -Wextra),它会被指出。

这是你需要什么?

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

int main (int argc, char **argv) 
{ 
    char buff[120]; 
    char text[120]; 

    printf("Enter your command: "); 

    fgets(buff, sizeof(buff), stdin); 

    buff[strlen(buff) - 1] = '\0'; /* get rid of the newline characters */ 

    sprintf(text, "echo StrText=\"%s\" > spk.vbs", buff); 

    system(text); 

    return 0; 
} 
+0

应用程序崩溃:/ –

+0

@OsandaMalith我还不确定你需要什么,但看到我的编辑。 – Nobilis

+1

是啊非常感谢!工作正常:) –

0

获得已弃用。改用fgets。

#include<stdio.h>                                                      

int main (int argc, char **argv) 
{ 
    char inputBuf[120]; 
    char cmdBuf[200]; 

    printf("Enter your name: "); 
    fgets(inputBuf , sizeof(inputBuf) - 1 , stdin); 
    sprintf(cmdBuf, "echo StrText=\"%s\" > spk.vbs" , inputBuf); 
    system(cmdBuf); 
    return 0; 
} 
+0

没有不工作:( –