2016-10-12 47 views
0
//all variables are declared in a struct StockPile 
//... 
string itemid;  
string itemdesc; 
string datepurchased; 
string line; 
int unitprice; 
int totalsales; 
std::string myline; 
//... 

void displaydailyreport() { 

    ifstream myfile("stockdatabase.txt"); 

    for(int i=0;std::getline(myfile,myline);i++) 
    { 
     // Trying to grep all data with a specific date from a textfile, 
     cout<<system("grep "<<stockpile[i].datepurchased<<" stockdatabase.txt")<<endl; 
    } 
    cout<<endl; 
} 

當我嘗試編譯它給了我這個錯誤:錯誤時使用C運行shell命令++ Ubuntu Linux操作系統

note:template argument deduction/substitution failed: 
Main.cpp:853:40: note: mismatched types ‘std::basic_ostream<_CharT, _Traits>’ and ‘const char [6]’ 
    cout<<system("grep "<<stockpile[i].datepurchased<<" stockdatabase.txt")<<endl; 

當我嘗試用這種運行正常工作:

cout<<system("grep '9oct16' stockdatabase.txt") 

stockpile[i].datepurchased是我可以在cout存儲在我的文本文件中的不同日期,我可以在for循環中打印出stockpile[i].datepurchased值。 它返回字符串9oct16,10oct16等,但當我嘗試使用shell命令它不會編譯。

+0

在''grep「<< stockpile [i] .datepurchased'中,編譯器找不到'<<'的意思。我也不能。 – v7d8dpo4

回答

4

<<運算符是一個流運算符。雖然您可以在一個流(如cout)上將字符串(和c字符串)與它們連接起來,但是如果不實際處理某個流,它不會以這種方式工作。

就讓我們走聲明系統調用單獨

"grep "<<stockpile[i].datepurchased<<" stockdatabase.txt" 

<<並不意味着使用這種方式沒有流對象「流」入內。

什麼可以做,雖然是這樣的:

std::string command = "grep " 
         + stockpile[i].datepurchased 
         + " stockdatabase.txt" 
system(command.c_str()); 

這確實幾件事情。

  • 創建std::string存儲系統命令
  • 因爲datepurchasedstd::string已經可以使用另一種C-字符串+運算符來連接它們。
  • 系統期待const char*作爲參數。因此,爲了能夠通過C-字符串的函數中,我們使用的std::string

c_str()功能還可以縮短語句如下:

system(("grep "+stockpile[i].datepurchased+" stockdatabase.txt").c_str()); 

因爲臨時std::string將創建通過+運營商,您可以直接訪問其功能c_str()

0

這是錯誤的:

cout<<system("grep "<<stockpile[i].datepurchased<<" stockdatabase.txt")<<endl 

你需要一個字符串流對象第一流命令的部分。 或者用串那樣建立命令:

std::string command = "grep "; 
command +=stockpile[i].datepurchased; 
command +=" stockdatabase.txt"; 

cout<<system(command.c_str())<<endl 
0

那麼,你的編譯器很清楚地告訴你,什麼是錯的:你要使用的流運算符<<有兩個不匹配的類型,即const char [6](又名"grep ")和std::ostream(又名stockpile[i].datepurchased)。你只是不能流入char數組或字符串。這就是STL設計的流。所以,一個可能的解決方案可能是:

std::cout << system((std::string("grep ") + stockpile[i].datepurchased + std::string(" stockdatabase.txt")).c_str()) << std::endl; 

沒有測試,雖然;)