【问题标题】:Creating and copying text to multiple .cpp files in C++在 C++ 中创建文本并将其复制到多个 .cpp 文件
【发布时间】: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(); 
}

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

【问题讨论】:

    标签: c++ copying


    【解决方案1】:

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

    【讨论】:

    • 说真的,我不知道这条线是做什么的std::string strNumber = static_cast&lt;std::ostringstream*&gt;(&amp;(std::ostringstream() &lt;&lt; Number))-&gt;str();。如果要将整数转换为字符串,请使用:std::stringstream ss; ss &lt;&lt; number; std::string strNumber = ss.str();,或者如果您正在运行 C++11 或更高版本,请使用 std::to_string
    • @ErvinSzilagyi 非常感谢!我一定会实施的。我认为这是一种相当复杂的方法,但这是 www.cplusplus.com/forum 上推荐的方法 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-28
    • 2019-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多