2013-01-07 33 views
-3

如何將連接的字符串參數傳遞給system()函數?如何將連接的字符串參數傳遞給system()函數?

  • 我使用GCC 4.5.2
  • 我必須做出std::string得到shell執行,其輸出 寫入到外部文件。
  • 我使用system()函數來執行此任務。

我無法執行此函數,因爲我只能傳遞char*參數而沒有std::string參數。

這裏是我的代碼..

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

using namespace std; 

void getch() 
    { 
    int c; 
    fflush(stdout); 
    while ((c = getchar()) != '\n' && c!= EOF) { /* Do Nothing */ } 
    } 

int main() 
{ 
string optTechniques[] = { 
     "-fauto-inc-dec", "-fcprop-registers", "-fdce", 
     "-fdefer-pop", "-fdelayed-branch", "-fdse", 
     ........, ....., ...... 
     } 
string str; 
str="gcc -Wall "+optTechniques[i]+" -o output"; 
cout<<"\n"<<str<<"\n"; /* Here it prints correctly */ 
system(str); /* This is generating error. */ 
string val; 
system("sh execTime.sh"); 

ifstream readFile("output.log"); 
readFile>>val; /* Works perfectly if execution is done. */ 
float execTime=strtof(val.c_str(),NULL); /* Converts the string to float */ 

getch(); 

cout<<"\nExecution Time: "<<execTime<<"\tTechnique: "<<optTechniques[i]<<"\n"; 
return 0; 
} 

更新:謝謝。我已經得到了答案。

+1

您是否編寫了此代碼?你到底懂不懂呢?如果是這樣,在這個語句中做了什麼'strtof(val.c_str(),NULL);'?具體來說,'val.c_str()'?如果你明白你可能已經知道答案了? –

+0

請發佈編譯和理解問題所需的最低代碼。這比發佈不必要的代碼好1000倍。例如。在代碼中getch'實現的必要性以及對'getch'的調用的必要性 – user93353

回答

4

從字符串中獲取字符指針c_str:。

system(str.c_str()); 
相關問題