如何使用for循环将数据保存在不同的文件中?
How to save the data in different files using for loop?
在下面的代码中,循环返回 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;
}
相关文章:
- 文件存在时的最新检查声明生成输入"is missing"
- GetPrivateProfileStringA 返回"The system cannot find the file specified."即使文件存在
- 自动工具: Makefile.am:如果文件存在,则链接
- 等待文件存在并且不被其他人占用
- 如何修复QFile打开错误(未知错误),即使文件存在
- WINAPI:文件存在检查失败
- 无法读取使用Unicode的文件(存在)
- C++检查文件存在而不打开它
- C++ 路径文件存在限制为 260 个字符
- 如何仅当文件存在时才使用追加模式打开文件
- 文件存在,但打开的文件仍始终返回 -1
- 路径文件存在导致链接器错误 2028/2019
- [UnixODBC][驱动程序管理器]无法打开 lib '/usr/lib/libmyodbc.so' :找不到文件,但文件存在
- 当文件存在时,Linux中的fopen(Lubuntu)会返回NULL
- 无法打开包含文件,尽管前面提到的文件存在
- std::ios::openmode的组合,如果文件存在,则截断,但防止创建新文件
- 当文件存在时,创建文件失败,错误码为2
- 没有这样的文件或目录,只有文件存在
- .cpp文件存在Xcode头文件问题
- 警告 LNK4099:如果文件存在,也找不到 PDB 'vc100.pdb'