你好,我的 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,所以谁能告诉我在不使用系统函数的情况下编写这个应用程序?
提前致谢。
最佳答案
将此添加到您的包含:
#include <string.h>
更改您的 char text;
至 char text[120];
- 必须是数组,而不是单个字符
然后替换gets
与 fgets
:
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 */
最后你通过了text
至 system
在根据您的目的对其进行格式化后(可能类似于):
sprintf(text, "echo StrText=\"%s\" > spk.vbs", buff);
这是您要找的吗?
注意:您还应该包括 #include <stdlib.h>
为你的system
称呼。始终编译时带有警告(gcc -Wall -Wextra
如果您使用的是 Linux),系统会为您指出。
这是你需要的吗?
#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;
}
关于C帮助批处理使用系统功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17628472/