繁体   English   中英

在C ++ Ubuntu Linux中运行Shell命令时出错

[英]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::stringc_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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM