【发布时间】:2009-08-02 13:55:37
【问题描述】:
我正在学习 C++ 并开发一个项目来练习,但现在我想在代码中转换一个变量(字符串),像这样,用户有一个包含 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;
}
这是一个文件示例:
code "time_t seconds;\n seconds = time (NULL);\n cout << seconds/3600;"
但是当我运行程序时,它不会将字符串转换为代码,而是准确地打印引号中的内容。
谢谢!
【问题讨论】: