[英]Error when running shell command in C++ ubuntu linux
//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;
}
當我嘗試編譯時,出現此錯誤:
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
存放在我的文本文件在不同的日期,我可以打印出stockpile[i].datepurchased
值在for循環。 它返回字符串9oct16,10oct16等,但是當我嘗試使用shell命令時,它將不會編譯。
<<
運算符是流運算符。 盡管您可以在流(例如cout
)上將字符串(和c字符串)連接在一起,但如果不實際在流上工作,它就無法正常工作。
讓我們將語句分別放在系統調用中
"grep "<<stockpile[i].datepurchased<<" stockdatabase.txt"
在沒有流對象“流”入的情況下, <<
不能用於這種方式。
但是,您可以執行以下操作:
std::string command = "grep "
+ stockpile[i].datepurchased
+ " stockdatabase.txt"
system(command.c_str());
這做了幾件事。
std::string
來存儲系統命令 datepurchased
已經是std::string
了,所以您可以在其他C字符串上使用+運算符將它們連接起來。 const char*
作為參數。 因此,為了將c字符串傳遞給函數,我們使用std::string
的c_str()
函數 您也可以將語句縮短為:
system( ("grep "+stockpile[i].datepurchased+" stockdatabase.txt").c_str());
因為一個臨時的std::string
將由+運算符創建,所以您可以直接訪問其c_str()
函數。
<<
是要附加到流的運算符,它不執行字符串連接。 因此,請使用+
而不是<<
來生成grep命令。
http://www.cplusplus.com/reference/string/string/operator+/
http://www.cplusplus.com/reference/string/string/operator%3C%3C/
這是錯誤的:
cout<<system("grep "<<stockpile[i].datepurchased<<" stockdatabase.txt")<<endl
您需要一個stringstream對象來首先流傳輸命令的各個部分。 或使用如下字符串構建命令:
std::string command = "grep ";
command +=stockpile[i].datepurchased;
command +=" stockdatabase.txt";
cout<<system( command.c_str() )<<endl
好吧,您的編譯器很清楚地告訴您出了什么問題:您正在嘗試將流運算符<<
與兩個不匹配的類型配合使用,即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;
不過沒有測試;)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.