c++ - 如何使用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;
}
解决方案
如果我理解你想要做什么,这里有一些基本的解决方案,用于演示,在当前文件夹中创建文件:
#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;
}
推荐阅读
- database - 将两个表的查询与另一个表连接起来
- android - 如何让导航视图上方的状态栏颜色在打开时发生变化
- c++ - 将单一 BGR 颜色转换为 HSV C++ OpenCV 4
- node.js - 如何将 Node-js 数据库查询绑定到 Web 表单
- ruby-on-rails - 猴子用 Rails 用业务逻辑修补核心类
- python - 将数据库中的表从不同服务器上的 MySQL 服务器复制到我的计算机
- php - 如果字符后跟数字,则替换字符
- gnuplot - 使用 gnuplot 的累积数据和外推
- arrays - perl - 将数组放入一个数组中
- css - 仅使用 css 将 bootstrap 4 汉堡图标更改为三点菜单图标的最佳方法