使用 fstream 从文件加载数据
Loading data from file using fstream
在文件 sequences.txt 中,有 100 个序列用两行描述。第一个表示此序列中的数字数量,而第二个包含此序列中的数字(数据以 space 分隔)。例如前四行是:
5
1 3 6 7 9
5
17 22 27 32 37
您能告诉我如何使用 fstream 库加载这些数据,以便我能够进行一些数学运算,例如计算每个序列的差异或它们的总和吗?我想我必须使用两个数组,一个用于每个序列中的数字数量,另一个用于每个序列中的数字。谢谢。
我编写了一个通用解决方案,它将您的文件放入二维锯齿状数组中。现在你的最终数组中有所有数据,你可以做任何你想做的任务。
文件
5
1 3 6 7 9
5
17 22 27 32 37
6
1 2 3 4 5 6
3
13 45 67
获取二维数组数据的代码。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string str;
ifstream in("File.txt");
int count = 4; //Your number of test cases here as you said 100 or 200
int *sizes = new int[count]; // all szies for your 1D arrays
int **Array = new int*[count]; //Main 2D array
for (int i = 0; i < count; i++)
{
in>>sizes[i]; //taking size for 1 row
Array[i] = new int[sizes[i]]; //Making arrays
for (int j = 0; j < sizes[i]; j++)
{
in >> Array[i][j]; //getting values of row
}
}
for (int i = 0; i < count; i++)
{
for (int j = 0; j < sizes[i]; j++)
{
cout << Array[i][j] << " "; //Printing Final Array [i,j]
}
cout << endl;
}
//Now you have your final array in Array which is 2D Jagged Array You Can Do What Ever You Want.
for (int i = 0; i < count; i++) //memory release
delete[] Array[i];
delete[] Array;
delete[] sizes;
system("pause");
return 0;
}
在文件 sequences.txt 中,有 100 个序列用两行描述。第一个表示此序列中的数字数量,而第二个包含此序列中的数字(数据以 space 分隔)。例如前四行是:
5
1 3 6 7 9
5
17 22 27 32 37
您能告诉我如何使用 fstream 库加载这些数据,以便我能够进行一些数学运算,例如计算每个序列的差异或它们的总和吗?我想我必须使用两个数组,一个用于每个序列中的数字数量,另一个用于每个序列中的数字。谢谢。
我编写了一个通用解决方案,它将您的文件放入二维锯齿状数组中。现在你的最终数组中有所有数据,你可以做任何你想做的任务。
文件
5
1 3 6 7 9
5
17 22 27 32 37
6
1 2 3 4 5 6
3
13 45 67
获取二维数组数据的代码。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string str;
ifstream in("File.txt");
int count = 4; //Your number of test cases here as you said 100 or 200
int *sizes = new int[count]; // all szies for your 1D arrays
int **Array = new int*[count]; //Main 2D array
for (int i = 0; i < count; i++)
{
in>>sizes[i]; //taking size for 1 row
Array[i] = new int[sizes[i]]; //Making arrays
for (int j = 0; j < sizes[i]; j++)
{
in >> Array[i][j]; //getting values of row
}
}
for (int i = 0; i < count; i++)
{
for (int j = 0; j < sizes[i]; j++)
{
cout << Array[i][j] << " "; //Printing Final Array [i,j]
}
cout << endl;
}
//Now you have your final array in Array which is 2D Jagged Array You Can Do What Ever You Want.
for (int i = 0; i < count; i++) //memory release
delete[] Array[i];
delete[] Array;
delete[] sizes;
system("pause");
return 0;
}