2013-07-13 90 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

沒有不工作:( –