2012-06-08 74 views
2

我有3個不同的命令行命令的字符串數組。我試圖學習如何將包含這些命令的字符串數組傳遞給for循環中的系統函數(或類似的函數,即exec()),而不是寫出3個系統函數。我在試圖弄清楚如何將這個字符串數組一次一個地傳遞給系統函數時遇到了困難。目標是要退出每個狀態並在返回錯誤時中斷for循環。將字符串數組傳遞給系統函數?

  std::string arrString[3] = {"something","another thing","a final thing"} 
      int i; 
      for(i=0; i<3; i++) 
      { 
       if (system(/*Something*/)) 
       ;//Do something... 
      }  

編輯:它輸出一個錯誤發生,但它不應該。

   std::string arrString[4] = {"cmd","cmd","cmd"}; 
      int i; 
      for(i=0; i<3; i++) 
      { 
       if (system(arrString[i].c_str())==0) { 
        OutputDebugStringW(L"It works!"); 
       } 
       else 
       { 
        OutputDebugStringW(L"It doesnt work :("); 
       } 
      } 

回答

3

system需要char*,所以你需要調用c_str您的陣列中的每個元素:

std::string arrString[3] = {"something","another thing","a final thing"} 
int i; 
for(i=0; i<3; i++) { 
    if (system(arrString[i].c_str())) { 
     //Do something... 
    } 
} 
+0

工作我如何需要。謝謝。在附註中,檢查退出狀態是否成功的最佳方法是什麼?請參閱上面的編輯* – arynhard

+0

'system(...)'返回命令返回的任何內容。通常,命令在成功時返回零,但確切的值取決於系統。您可以將返回碼分配給一個「int」變量,並檢查該值以確定運行是否成功。 – dasblinkenlight

+0

因此,使用'if(system(arrString [i] .c_str()== 0)'這樣的東西不是最好的選擇嗎?我聽說system()的返回並不總是可靠的。我只是想找到最好的解決方案。 – arynhard

0
system(arrString[i]) 

然後檢查退出代碼,如果合適的破環。

0

你必須使用c_str()功能std:string轉換爲char*第一:

system(arrString[i].c_str())