使用C ++

时间:2017-03-18 20:34:58

标签: c++ copying

所以我正在进行Euler项目,我将所有解决方案存储在一个程序中。我刚刚开始使用C ++,所以我不知道这是否是一个很好的方法。无论如何,每个.cpp文件都包含一个问题。所以基本上我的结构是这样的:

“Executer.cpp”

include <iostream>
include "other.h"
int main() {

    Problem1();
    Problem2();
    // etc.
    system("pause")
    return 0;
}

“Other.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”的文本文件中。然后我写了下面的程序,我从我的int main运行,在“other.h”中包含函数声明,并从“Executer.cpp”调用函数。将文本从一个文本文件复制到另一个文本文件时,它运行正常。但现在(我假设因为我试图复制到.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(); 
}

有没有人有经验做这样的事情?我在谷歌上找不到任何帖子,而且我不知道在哪里看。

1 个答案:

答案 0 :(得分:0)

程序实际按预期运行。它恰好创建了新的“Problem_X.cpp”文件。它们只是不在VS源文件夹中导入。如果有人有这方面的快速解决方案,欢迎他们在这里发表评论。