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

How to save the data in different files using for loop?

本文关键字:文件 存在 保存 for 何使用 循环 数据      更新时间:2023-10-16

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

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

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

使用文件流。

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