首页 > 解决方案 > 如何使用for循环将数据保存在不同的文件中?

问题描述

在下面的循环代码中,我返回了 5 个值 [0,1,2,3,4]。我想获得 5 个名为 h_0.0、h_1.0、h_2.0、h_3.0、h_4.0 和 h_0.0 的文本文件应该存储第一个 for 循环数,即 0 文件 h_1.0 应该存储第二个for 循环的数量,即 1 等等。

#include <iostream>
using namespace std;

int *name()
{
    static int n[5];
    for (int i = 0; i < 5; i++)
    {
        n[i] = i;
    }
    return n;
}

int main()
{
    int *p;
    p = name();
    for (int i = 0; i < 5; i++)
    {
        cout << *(p + i) << endl;
    }
    return 0;
}

标签: c++

解决方案


如果我理解你想要做什么,这里有一些基本的解决方案,用于演示,在当前文件夹中创建文件:

#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;

int* name() {
    static int n[5];
    for (int i = 0; i < 5; i++) {
      n[i] = i;
    }
    return n;
}

int main() {
    int* p;
    p = name();
    for (int i = 0; i < 5; i++)
    {
        int fn = *(p + i);
        std::stringstream ss;
        ss << fn;
        std::string fname = "h_" + ss.str();
        fname += ".0";
        std::ofstream f(fname.c_str());
        if (f.good()) {
            f << fn;
            cout << "file h_" << fn << ".0 created" << endl;
        }
    }
    return 0;
}

推荐阅读