如何使用for循环将数据保存在不同的文件中?

时间:2019-09-16 23:32:48

标签: c++

在下面的循环代码中,我返回了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;
}

2 个答案:

答案 0 :(得分:1)

如果我很了解您想做什么,这是演示的一些基本解决方案, 在当前文件夹中创建文件:

#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;
}

答案 1 :(得分:0)

使用文件流。

#include <fstream>  // include filestream
#include <sstream>  // for storing anything that can go into a stream
#include <string>

int main()
{

    std::string nameholder;
    std::ofstream outputstream;

    for (int i = 0; i < 5; i++)
    {
        nameholder = "h_";  // reset name every loop
        std::stringstream sstreamholder;   // remake stringstream every loop
        sstreamholder << i;   // store current number in stringstream
        nameholder += sstreamholder.str() + ".0";  // append what sstreamholder currenlty has and the file extension .0
        outputstream.open(nameholder);  // write the filename with the updated name
        outputstream << i << std::endl;  // write the number in the file
        outputstream.close();  // close the file so it's ready for the next open
    }
    return 0;
}