1. 二维文本数据
- 读数据
const int M = 256;
const int N1 = 256;
const int N2 = 256;
static int ImageData1[M * N1];
static int ImageData2[M * N2];
static int ImageDataOut[M * (N1 + N2)];
static int outp[M][N1 + N2];
int num;
int ImageMove = 0;
//读取数据256*256
ifstream file1("10_1.txt", ios::in);
num = 0;
if (file1.is_open() == false)
{
cerr << "Error!" << endl;
exit(-1);
}
while (file1 >> ImageData1[num*N1 + 0])
{
for (int i = 1; i < N1; i++)
{
file1 >> ImageData1[num*N1 + i];
}
num++;
}
file1.close();
- 写数据
ofstream os("output.txt", ios::app);
ofstream("output.txt").close(); // 清除原有内容
if (os)
for (int i = 0; i < M; i++)
{
for (int j = 0; j < (N1 + N2); j++)
os << outp[i][j] << " ";
os << endl;
}
else
cerr << "无法打开文件!" << endl;
2. 一维文本数据
- 读数据
float *echo = new float[M]; // 动态分配内存
ifstream inFile;
inFile.open("echo.txt");
k = 0;
if (!inFile.is_open())
{
cout << "Error! Program terminating.\n";
exit(EXIT_FAILURE);
}
while (!inFile.eof() && k < M)
{
inFile >> echo[k];
k++;
}
inFile.close();
inFile.clear();
- 写数据
ofstream outFile;
outFile.open("T2.txt");
for (i = 0; i < N; i++)
outFile << x[i] << endl;
outFile.close();
3. 动态数组
vector sig;
ifstream sig_inp("file.txt");
if ( !sig_inp.good())
{
cout << "The File doesn’t exist"<< endl;
}
while (sig_inp)
{
double temp;
sig_inp >> temp;
sig.push_back(temp);
}
sig.pop_back();