【发布时间】:2017-03-18 20:34:57
【问题描述】:
所以我正在执行 Euler 项目,并将我的所有解决方案存储在一个程序中。我刚刚开始使用 C++,所以我不知道这是否是一个好方法。无论如何,每个 .cpp 文件都包含一个问题。所以基本上我的结构是这样的:
“执行者.cpp”
include <iostream>
include "other.h"
int main() {
Problem1();
Problem2();
// etc.
system("pause")
return 0;
}
“其他.h”
void Problem1();
void Problem2();
// etc.
“Problem_X.cpp”(X 表示任务的编号)。我有很多这样的文件。
/* PROBLEM X
*/
#include <iostream>
#include <fstream>
#include <time.h>
void ProblemX() {
time_t t1, t2;
t1 = clock();
// Code goes here
t2 = clock();
float diff((float)t2 - (float)t1);
float seconds = diff / CLOCKS_PER_SEC;
// Results
std::ofstream myFile("result.txt");
//myFile << sum;
myFile.close();
std::cout << "-------------------- Problem X -------------------" << std::endl;
std::cout << "I ran for: " << seconds << " seconds" << std::endl << std::endl;
}
现在,项目包含近 600 个问题,这意味着我必须创建 600 个文件并将模板复制到每个文档中。所以我想我可以做一个程序来做这件事。
基本上,我将“Problem_X.cpp”放入名为“standard.txt”的文本文件中。然后我编写了以下程序,我通过在“other.h”中包含函数声明并从“Executer.cpp”调用该函数,从我的 int main 运行该程序。将文本从一个文本文件复制到另一个文本文件时,它运行良好。但是现在(我假设因为我试图复制到 .cpp 文件中)什么都没有发生:
#include <fstream>
#include <iostream>
#include <sstream>
void CreateNewFile(int number) // denotes the number of the problem you wish to create
{
std::string strNumber = static_cast<std::ostringstream*>(&(std::ostringstream() << Number))->str();
std::string str1 = "Problem_";
std::string str2 = ".cpp";
std::string strr;
strr.append(str1); strr.append(strNumber); strr.append(str2);
std::ofstream out(strr); //this creates it.
std::ifstream in("standard.txt");
if (!out.is_open())
{
std::cout << "ERROR: Can not open document2.txt" << std::endl;
return;
}
std::string str;
while (std::getline(in, str)) {
out << str << std::endl;
}
in.close();
out.close();
}
有没有人做过这样的事情?我在谷歌上找不到任何帖子,而且我不知道去哪里找。
【问题讨论】: