如何将连接的字符串参数传递给system()函数

How to pass a concatenated string argument to the system() function?

本文关键字:system 函数 参数传递 字符串 连接      更新时间:2023-10-16

如何将连接的字符串参数传递给system()函数?

  • 我使用GCC 4.5.2
  • 我必须使std::stringshell中执行并写入其输出
  • 我使用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;
}

更新:谢谢。

从字符串c_str:.

获取char指针
system(str.c_str());