我正在学习C++并开发一个项目来练习,但现在我想在代码中转换一个变量(String),像这样,用户有一个包含C++代码的文件,但是我希望我的程序读取该文件并插入它进入代码,像这样:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main( int argc, char* argv[] )
{
ifstream file(argv[ 1 ]);
if (!file.good()) {
cout << "File " << argv[1] << " does not exist.\n";
return 0;
}
string linha;
while (!file.eof())
{
getline(file, linha);
if (linha.find("code") != string::npos)
{
size_t idx = linha.find("\""); //find the first quote on the line
while ( idx != string::npos ) {
size_t idx_end = linha.find("\"",idx+1); //end of quote
string quotes;
quotes.assign(linha,idx,idx_end-idx+1);
// do not print the start and end " strings
cout << quotes.substr(1,quotes.length()-2) << endl;
//check for another quote on the same line
idx = linha.find("\"",idx_end+1);
}
}
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是一个文件例子:
code "time_t seconds;\n seconds = time (NULL);\n cout << seconds/3600;"
Run Code Online (Sandbox Code Playgroud)
但是当我运行程序时,它不会将字符串转换为代码,但它会精确打印引号中的内容.
谢谢!
C++是一种编译语言,而不是解释语言.
因此,程序无法即时读取C++代码并执行它,因为此代码需要编译.