Files
python/C++专题课程/文件输入与输出/readOneDimensionArray.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

69 lines
1.3 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include<bits/stdc++.h>
using namespace std;
//开一个准备读取数据的数组
int const N = 10;
//数组初始化
int arr[N] = {0};
//模拟第一个数据n
int n;
/**
* 功能:从数据文件读取数据填充一维数组
* 作者:黄海
* 时间2019-11-02
*/
void readOneDimensionArray() {
//数据源文件
string file = "./data.in";
//1、读取数据到数组的方法
ifstream fin(file);
//读取n
fin >> n;
//和cin一样读取一维数组
for (int i = 0; i < n; i++)
fin >> arr[i];
//关闭文件
fin.close();
fin.clear(ios::goodbit);
}
int main() {
//读取一维数组文件
readOneDimensionArray();
cout << "1、下面将打印第一个数字n的内容" << endl;
cout << "n=" << n << endl;
cout << endl;
cout << "2、下面将打印读取到的数据内容" << endl;
//输出一下读取到的内容
for (int i = 0; i < N; i++) {
cout << arr[i] << " ";
}
cout << endl;
//===========================================================================
//2、输出数据
string file = "./data.out";
//输出
ofstream fout(file);
//输出数组
for (int i = 0; i < N; i++) {
//内容
fout << arr[i] << endl;
cout << arr[i] << endl;
}
//关闭文件
fout.close();
//提示信息
cout << "恭喜,成功输出到文件" + file + "中!" << endl;
//===========================================================================
return 0;
}