在C++代码中转换字符串

Nat*_*pos 0 c++ string

我正在学习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)

但是当我运行程序时,它不会将字符串转换为代码,但它会精确打印引号中的内容.

谢谢!

Thi*_*hib 5

C++是一种编译语言,而不是解释语言.

因此,程序无法即时读取C++代码并执行它,因为此代码需要编译.

  • 你在和这个家伙一起浪费时间. (6认同)
  • 尼尔,我也经常这么想,但另一方面,如果你不解释它们,有些人就不会学习东西 - 而且会浪费更多的时间和其他时间. (2认同)
  • @Nathan:您对C++(和其他命令式语言)的工作方式存在根本性的误解.你必须重做这个,而不仅仅是在C++中成为"新手"的基础上抛弃它. (2认同)